Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice for a module to recursively import its submodules?

Tags:

python

I see a common pattern with Python modules. Sometimes __init__.py imports its submodules:

E.g.

mymod/
    __init__.py:
        from . import subm1, subm2
        __all__ = ['subm1', 'subm2']

    subm1.py:
        def subf1():
            ...
        __all__ = ['subf1']

    subm2.py:
        def subf2():
            ...
        __all__ = ['subf2']

So the client code only has to do this:

import mymod
mymod.subm1.subf1()
mymod.subm2.subf2()

Instead of:

import mymod.subm1
import mymod.subm2
mymod.subm1.subf1()
mymod.subm2.subf2()

Which one is The Best PracticeTM? Is there anything wrong with the recursive import or should I stick to the default behaviour? What's the rationale for the default behaviour?

like image 388
Alex B Avatar asked May 18 '12 04:05

Alex B


People also ask

Why can’t I import a module in Python?

Since there are no finders, Python can’t find or import new modules. However, Python can still import modules that are already in the module cache since it looks there before calling any finders. In the example above, importlib was already loaded under the hood before you cleared the list of finders.

What are modules in Python?

Modules have a namespace containing arbitrary Python objects. Modules are loaded into Python by the process of importing. ( Source) In practice, a module usually corresponds to one .py file containing Python code. The true power of modules is that they can be imported and reused in other code.

What are the advantages of a submodule in a project?

Each submodule can be used by multiple parent projects. Each parent project has control over which release of each subsidiary project is being used, and each parent project can push changes to the subsidiary projects. Those attributes are a rough summary of the advantages.

How to get access to code from another module in Python?

Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.


1 Answers

This would depend on the usage of your module. If the submodules are just singleton objects that happen to be written as modules instead of having, eg, Java-like classes with all-static methods, recursive import is probably fine. On the other hand, if your module is grouping of several related sub modules (see, eg, the stdlib html module), you would want explicit submodule imports.

In general, a recursive import setup says "any client of this module will always want all of these". Consider whether that is true for your module (and other modules, case-by-case), and go from there.

like image 161
lvc Avatar answered Nov 09 '22 23:11

lvc