1

I can't figure out how to solve an issue I have when using reload in my program. If my code is like

import mymodule
from mymodule import MYCLASS

x = MYCLASS()

then everything works fine. However if I try to reload the module like this:

import mymodule
from mymodule import MYCLASS
x = MYCLASS()
reload(mymodule)
y = MYCLASS()

I get some weird error. I understand that maybe is because the reference of MYCLASS and of mymodule have changed, but can't understand exactly why and how to prevent it.

What is the correct way to reload modules and classes imported in such a case?

0

1 Answer 1

3

You should use reload in following style.

import mymodule
x = mymodule.MYCLASS()
mymodule = reload(mymodule)
y = mymodule.MYCLASS()

http://docs.python.org/2/library/functions.html#reload

If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.name) instead.

UPDATE

isinstance(x, mymodule.MYCLASS) will be False, as the class is reinitialized, but x.__class__ still references the old class.

>>> isinstance(x, mymodule.MYCLASS)
False
>>> isinstance(y, mymodule.MYCLASS)
True
Sign up to request clarification or add additional context in comments.

1 Comment

+1. It's worth to mention that after doing something like this, isinstance(x, mymodule.MYCLASS) will be False, as the class is reinitialized, but x.__class__ still references the old class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.