Search code examples
pythonpython-3.xipythonspyder

Change global variable from another module in Spyder


I have a module which only contains variables to be used as settings

#Settings.py 
settings = {'a' : 0, 'b': True}

These variables are called around in the code in a similar manner :

from Settings import settings 
def f(x): 
    return settings['a'] * x 

I have a function which tests out different settings by modying them

#main.py
def test() : 
    import Settings 
    Settings.settings['a'] = 2 
    f(x)
    Settings.settings['a'] = 4
    f(x) 
    Settings.settings['b'] = False 
    f(x)
    .... 

test()

This code works on my Unix deployement system and the modifications done to settings are propagated to the rest of the code. I code and test on Windows 10 with Spyder on an Ipython console.

On my testing environnement, the changes are not considered and settings is never modified in main.py.

What happens in Spyder / Ipython for it to not consider the changes done to settings and how can i be sure that this doesn't happen in the future?


Solution

  • This has to do with the way spyder caches your loaded variables. As spyder loads in a specific module the cache is not adjusted. I have had this error a few times, usually clearing the cache by resetting spyder works for me.

    The best way to tackle this is to use a local settings Class that you can adjust like so:

    class Settings:
        def __init__(self):
            self.a = 1
            self.b = True
    

    Then you can do:

    from Settings import Settings
    
    def f(x, settings):
        return settings.a * x
    
    def test():
        settings = Settings()  # Create an instance of Settings
    
        # Modify the settings and use them
        settings.a = 2
        print(f"settings.a after setting to 2: {settings.a}")
        print(f(x, settings))  # Use the settings instance in the function
    

    Hope this helps!