Search code examples
pythonfunctionvariablesscopepython-module

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


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

Solution

  • 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