How to import only a submodule in Python?

I have this structure:

. └── module ├── __init__.py └── submodule ├── __init__.py ├── foo.py └── bar.py 

In module.submodule.__init__.py , I have this:

 import foo import bar 

In module.submodule.foo.py , I have this:

 import very_heavy_third_party_module as vhtpm ... 

I would like to import only bar , but I slowed down on foo (suppose there is an ugly time.sleep(3) in foo and module/__init__.py ).

So, my goal is to write this below without slowing down the other parts of my module:

 from module.submodule.bar import saybar saybar() 

How do I import saybar into my bar submodule?

+5
source share
1 answer

The only way to import from bar without running foo is to remove import foo from module.submodule.__init__.py . This is due to the fact that when importing a package / module in Python, all the top-level code in this module is run (or __init__.py when importing the package). When you run from module.submodule.bar import saybar , all the top-level code:

  • module.__init__.py
  • module.submodule.__init__.py
  • module.submodule.bar.py
Performed

. Since module.submodule.__init__.py contains import foo , foo imported, and all its top-level code (including import very_heavy_third_party_module as vhtpm ) also starts, which leads to a slowdown.

Several possible solutions:

  • Move as much code as possible from __init__.py . It is common practice to leave __init__.py empty - if there is any functionality there, you might consider moving it to your own module. Once the import strings are single, you can simply delete them, as they have nothing to do with the namespace.
  • Move import vhtpm in foo.py down from the top level (for example, to a function called by something else in the module). This is not very clean, but may work for you if you need optimization.
+3
source

Source: https://habr.com/ru/post/1259163/


All Articles