Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a submodule alone 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 bar only, but I got slowed down by foo (let's imagine there is an ugly time.sleep(3) in both foo and module/__init__.py).

So my goal is to write this below without getting slowed down by other parts of my module:

from module.submodule.bar import saybar
saybar()

How can I just import saybar located in my submodule bar?

like image 748
nowox Avatar asked Oct 17 '22 23:10

nowox


1 Answers

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

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

is run. Since module.submodule.__init__.py contains import foo, foo is imported and all of its top-level code (including import very_heavy_third_party_module as vhtpm) is run as well, causing the slowdown.

A few possible solutions are:

  • Move as much code as possible out of __init__.py. It's a common practice to leave __init__.pys empty - if there's some functionality in there, you might want to consider moving it to its own module. Once the import lines are the only ones remaining, you can just remove them, since they make no difference with regards to namespacing.
  • Relocate the import vhtpm in foo.py down from the top-level (e.g. into a function that's called by something else in the module). This isn't very clean, but might work for you if you need the optimization.
like image 82
Noah Avatar answered Nov 01 '22 10:11

Noah