Search code examples
python-2.7global-variablesreloadvolatiledynamic-import

How to dynamically import and reimport a file containing definition of a global variable which may change anytime


I need to have actual state of my List, which may change anytime.

mylist.py

list = {"key": "value"}

For first time import it's state is actual, but list in mylist.py may be changed. I need to reimport it each time function is called.

somecode.py

def someFunc():
    from mylist import list
    print list

Solution

  • There is a function called reload(module)

    import mylist 
    
    def someFunc():
        mylist = reload(mylist) # this may raise syntaxerrors in wrong moments
        list = mylist.list
        print list
    

    Does it work for you?