Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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:

  1. Omit import math from "main.py" becuase it's redundant? Or,
  2. Keep import math in "main.py" to clarify that the code in that module requires it?
like image 833
nerdfever.com Avatar asked Jan 01 '23 23:01

nerdfever.com


2 Answers

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).

like image 61
jwodder Avatar answered Jan 04 '23 13:01

jwodder


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.

like image 23
MarianD Avatar answered Jan 04 '23 12:01

MarianD