Skip to content Skip to sidebar Skip to footer

Best Practice For Nested Python Module Imports

Suppose I have a Python module 'main.py': import math # from the standard Python library import my_own_module ... foo = math.cos(bar) And I also need to import the sta

Solution 1:

The reference to math.cos in main.py means that import math is required in main.py, regardless of whether my_own_module.py imports it or not. It is not redundant, and it cannot be omitted (and if you try to omit it, you'll get an error).

Solution 2:

import math

does something else than simply including the full text of one file into the other.

It introduces a new namespace with the name math, and this math name will be known in your current namespace.

If you omit the

import math

from your main.py file, your command

foo = math.cos(bar)

becomes illegal, as the math symbol will be not (recognized) in the main.py namespace.

Solution 3:

This is not like, eg #include in C++. The import is not optional. Importing a module is required to be able to refer to its contents. This is true for every single file that does it.

Solution 4:

A good question. The short answer is yes, if you use a math function in a py file then you need to import the module at the top regardless of how many times its imported elsewhere.

It gets interesting when we throw a thrid file into the mix, lets call this "explanation.py"

And lets suppose that your "main.py" becomes "my_functions.py" and contains a function called foo:

#my_functions.pyimport math
import my_own_module
deffoo(bar):
    return math.cos(bar)

and in my_own_module.py:

#my_own_module.pyimport math
defbar(foo):
    return math.sin(foo)

and finally explanation.py (new main())

#main.pyimport my_functions
import my_own_module
bar = my_functions.foo(10)
foo =  my_own_module.bar(10)
print(foo)
print(bar)

Notice how you DO NOT need to add math if you call the functions imported from another file. I hope that might add further clarity to your enquiry :)

However it might be worth noting that this would exclude maths from the current namespace, therefore rendering any further calls to the math functions useless.

Post a Comment for "Best Practice For Nested Python Module Imports"