4

When I import a class MyClass from a file myModule.py from with a myModules dictionary i do it like

from myModules.myModule import MyClass

How to reload this module after I have made changes to the file myModue.py? Here are some mistrials:

reload(MyClass) # TypeError: reload() argument must be module
reload(myModule) # NameError: name 'myModule' is not defined
reload(myModules.myModule)  # NameError: name 'myModules' is not defined
2

1 Answer 1

3

You must have a module to reload. when you use the from foo import bar, unless bar is a module (it looks like it isn't, in your case) you will have to use another import statement.

from myModules.myModule import myClass
# this will cause myModule.py to be evaluated.  only myClass is in scope

from myModules import myModule
# since myModule has already been imported, myModule.py is not evaluated again. 
# but now myModule is in scope.

reload(myModule)
# this will cause myModule.py to be evaluated again.

If, for some reason, you don't want two imports, the already imported module can also be found in sys.modules

Sign up to request clarification or add additional context in comments.

3 Comments

Is it considered bad style when importing classes as I do? Or does it not matter?
It's not bad style. It depends what you need from an import. If you only need MyClass, you import only MyClass. If you need everything in MyModule, you import MyModule (and access MyClass with MyModule.MyClass)
I personally prefer to always import modules, but this is not the reason. Using modules can keep you out of circular import trouble, and also tends to reduce the total number of global names for the reader to keep track of. If you are concerned about how your imports are interacting with reload(), then you probably are doing something wrong, it's only reasonable useful when programming interactively, to reload a module's contents that you have changed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.