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?
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.
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.
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.
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.
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.
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