1

I have a utils.py file in which I store most of the functions that I use in my main code. Just to be safe, I import a lot of the common libraries such as numpy, pandas, etc. in the main code as well as in the utils.py.

However, while spring-cleaning my code today, I was wondering if that is the best way to import libraries. I realize that Python does not re-load the module that has already been loaded (unless explicitly asked to reload numpy as np). But if I import numpy as np in utils.py, do I need to import these libraries again in the main code files? I think that if I import libraries in the main code, then their namespace should be globally available, and thus I won't have to import them again in the utils.py. Is that correct?

bluetooth
  • 529
  • 6
  • 20
  • Possible duplicate of [What is the most pythonic way to import modules in python](https://stackoverflow.com/questions/6372159/what-is-the-most-pythonic-way-to-import-modules-in-python) – Alex Mar 29 '18 at 19:17
  • 1
    Another possible duplicate [What happens when a module is imported twice?](https://stackoverflow.com/questions/19077381/what-happens-when-a-module-is-imported-twice) – Evan Nowak Mar 29 '18 at 19:18

1 Answers1

0

It is not correct.

An imported module won't see the namespace of the importer. Its global namspace would be the globals of its own file.

While the importer can see into the imported namespace by qualifying with the module name, the other way round will not work.

Say you have module1.py and utils.py

module1.py:
import sys
import utils

utils.print_args()

utils.py:
# import sys

def print_args():
    print(sys.argv)

Running module1.py without uncommenting the import sys in utils.py will give

NameError: name 'sys' is not defined

After uncommenting you get

['module1.py']
progmatico
  • 4,714
  • 1
  • 16
  • 27