0

consider this foo.py:

bar = 'baz'

when I

from foo import bar

in foo.py is there find out that only bar is imported, and not the whole module, or * or something else?

Background

The actual code is a package / a package's __init__.py where a bunch of imports from the rest of the package happen that expose what's typically used. But when importing specific objects, all of that could be skipped. Some of those imports are rather heavy.

chichak
  • 613
  • 1
  • 5
  • 9
  • 2
    The whole file is _always_ imported. In your example, only `bar` is _added to the namespace_, but everything else still exists. It's possible to tell when the module is loaded (because that's when the code runs) and when something is _used_, but not what specific names are imported. You might be able to use the `@property` decorator or [a module-level equivalent](https://stackoverflow.com/a/60120256) to detect the first time a variable is accessed and initialize it lazily. – Green Cloak Guy Jun 17 '20 at 13:05
  • It's standard practice to accept that the entire module is loaded when only part of it is used. For example, in your python interpreter, go try to import just one object from a very large module (e.g. `from pandas import DataFrame`) and compare it to how long it takes to import the entire module (`import pandas`). Should be the same. – Green Cloak Guy Jun 17 '20 at 13:08
  • Sure, that's what usually happens. I'd like to avoid that because it takes a lot of time. And I can definitely import something conditionally, consider: `import os ; if os.urandom(1)[0] % 2: import pandas` - that will import pandas randomly 50% of time. The question is: can I conditionally import it when necessary? - the module level equivalent of @property may be something, I'll look into it, thanks! – chichak Jun 19 '20 at 09:11

0 Answers0