Home > Enterprise >  How to change the value of a variable before importing a module in python?
How to change the value of a variable before importing a module in python?

Time:06-01

Suppose I have a config.py file that has some variables,

# config.py
LIFE = 1
MONEY = 200

And I will have to import a function which uses those variables within itself,

# game.py
from config import LIFE, MONEY

def live():
    if MONEY < 1000:
        print("Money:", MONEY)
        return 'GAME OVER'
    
    else:
        print('Money:', MONEY)
        return 'LIVED ONE DAY'

And suppose I went into testing phase, and I have to test the 'game.live' function. But I have no write permissions in either of the game.py or the config.py . How do you think I could change the value of, say, MONEY variable before calling the 'game.live' function such that the value of MONEY also changes in the 'game.live' function?

For example,

# test.py
from config import MONEY, LIFE
MONEY = 20000000000000

from game import live
print(live())

>> Money: 20000000000000
>> LIVED ONE DAY

CodePudding user response:

If you change how things work, then its possible to test:

# game.py
import config

def live():
    if config.MONEY < 1000:
        print("Money:", config.MONEY)
        return 'GAME OVER'
    
    else:
        print('Money:', config.MONEY)
        return 'LIVED ONE DAY'

Similarly change the test:

# test.py
import config
config.MONEY = 20000000000000

from game import live
print(live())

Output as requested

CodePudding user response:

I think the best way is to use a database and a file that manages his content.

You can find some examples for python by searching for "sqlite3 example python" it's simple to use.

Good luck with this

  • Related