1

This is a theoretical question that I have been looking for an answer to for sometime, but could never actually find it.

Suppose I have my main file main.py which has import numpy as np and import helper.

If I have a helper file helper.py, could I use np in helper.py, because I already imported it in main.py, and the only time I would ever use helper.py is via main.py, resulting in numpy always being imported?

2

1 Answer 1

1

No. The python documentation states:

The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope.

If the import occurs at the top of a module, local scope will be global - i.e. local to the module.

On the plus side, normally imports will only occur once. Python will search the cache for imports before carrying out an import and will create a reference to a previously imported module if it finds it. This saves have to load a second copy - there's no harm (generally) in having the import statement in both modules.

The first place checked during import search is sys.modules. This mapping serves as a cache of all modules that have been previously imported, including the intermediate paths.

Additionally, from the FAQs:

How do I share global variables across modules?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application;

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.