Suppose I have a python module called mymodule
. At the top of my Code, I have this:
import mymodule
reload(mymodule)
where my directory structure is
/dir/mymodule.py
However, I would like to split mymodule.py
into several files, while still being defined as a single module (i.e. I don't want to have to import each file separately - I want to be able to use my import/reload as before).
The only way I know how to do this is the following
/dir/mymodule/
file1.py
file2.py
__init__.py
where __init__.py
contains
from file1 import *
from file2 import *
This mostly works, but my call to reload(mymodule)
no longer does anything, because it doesn't reload anything called via * imports.
Any suggestions?
There are actually three different ways to define a module in Python: A module can be written in Python itself. A module can be written in C and loaded dynamically at run-time, like the re (regular expression) module. A built-in module is intrinsically contained in the interpreter, like the itertools module.
Steps used to open multiple files together in Python: Both the files are opened with an open() method using different names for each. The contents of the files can be accessed using the readline() method.
For a quick workaround I could suggest
import sys
def myreload(base_module_name):
for module_name, module in sys.modules.items():
if module_name.startswith(base_module_name):
reload(module)
myreload('mymodule')
This would call reload(mymodule.file1)
, reload(mymodule.file2)
etc.
However, it is not recursive and as you are using ipython, I believe your quiestion is well answered here.
I'm not sure exactly why you're doing this, but will assume you have you reasons. I think this works:
__init__.py:
import file1
reload(file1)
from file1 import *
Obviously you can import file2 as well
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With