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 standard math module in "my_own_module.py":
import math
...
baz = math.sin(qux)
In this case I think import math
in "main.py" is redundant and can be omitted.
What's best practice in this case:
import math
from "main.py" becuase it's redundant? Or,import math
in "main.py" to clarify that the code in that module requires it?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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With