Skip to content Skip to sidebar Skip to footer

Do A Python Module's Imports Need To Be Carried Over When Importing That Module?

It's late and I'm confused about imports within imports (within imports). For this question, you'll have to bear with my 'apps' and 'helpers' as they are merely vehicles for an exp

Solution 1:

Consider the following two scripts:


module1.py

import random
import module2

module2.py

printrandom.random()   # NameError: name 'random' is not defined

module2 does not know about random, and may very well define its own object named random. As much as that is discouraged, it is not forbidden. In the case of random, a built in module, it is expected that one wouldn't shadow it. But there are thousands of other packages one could download, all using their own module names. You can't be expected to avoid all of them.

So to use the functionality of a module, be it built in like random, a downloaded package, or your own, the calling module must import it. Otherwise it cannot know about it.

There is very little overhead to importing a module in multiple places. The code is not loaded twice. It is only referenced twice.


In short, import what you need in the modules in which you need it.

Solution 2:

If the expression datetime.date appears only in app_helper.py, then the only module that has to import datetime is app_helper.py.

Similarly, if the only module that the expression random.random appears in is app_helper_helper.py, then the only module that needs to import random is app_helper_helper.py.

Higher-level modules can live in blissful ignorance of what the lower-level modules are importing.

Solution 3:

If code within module A (that is, code written in A.py) needs to use module B, module A needs to import module B. That's it.

So if app_helper makes reference to datetime, it needs to do import datetime (or from datetime import datetime or some such thing, depending on what exactly it needs to use). If app does not make reference to datetime, it does not need to do import datetime.

Post a Comment for "Do A Python Module's Imports Need To Be Carried Over When Importing That Module?"