Search code examples
pythonimportmodulepackagereload

Python 2.7 - Keep two working versions of package in memory


Is it possible to do smth like that without breaking anything:

import some
some_copy = some
print some.version  # v1.0

# modify code and reload package
# ...
print some.version  # v1.1
print some_copy.version  # v1.0

So I want to have two different versions of module/package running simultaneously (in one process).


Solution

  • Assume you have two scripts. The first, called some.py like this one

    class some(object):
        def __init__(self):
            self.version = '1.0'
    

    and the other one, called wcode.py. Executing it

    import some
    some1 = some##.some()
    
    raw_input("Waiting for you to change '1.0' into '1.1'.\nPress ENTER when done.")
    
    reload(some)
    some2 = some##.some()
    
    print(some1().version)
    print(some2().version)
    

    prints

    1.0
    1.0
    

    Why ? Simply because the imported definition of some is overriden. Which means that you may want to instantiate it so as to keep its methodes defined as in the first version class. As follows

    import some
    some1 = some.some()
    
    raw_input("Waiting for you to change '1.0' into '1.1'.\nPress ENTER when done.")
    
    reload(some)
    some2 = some.some()
    
    print(some1.version)
    print(some2.version)
    

    prints

    1.0
    1.1
    

    So the answer is NO conditionnally, what you want to do is not possible whithout instantiating your first version class before reloading the module. As done above, actually. Note that why in the world you want to do this is beyond me. But you may have good reasons.