Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Define a module by several files

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?

like image 503
rottweiler Avatar asked Apr 18 '13 22:04

rottweiler


People also ask

What are the three different ways to define a module in Python?

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.

Can you use multiple files in Python?

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.


2 Answers

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.

like image 62
Ixanezis Avatar answered Oct 20 '22 10:10

Ixanezis


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

like image 25
GeorgeWilson Avatar answered Oct 20 '22 11:10

GeorgeWilson