Reputation: 170
If I have two files:
file1.py, which contains functions that would be shared across different files:
def log(x):
return math.log(x)
file2.py
import file1
import math
print(file1.log(math.e))
However, when I run python file2.py
I get the following error: NameError: name 'math' is not defined
. Is there a way to avoid re-importing a module in an imported module when the importing module had already imported it?
Alternatively, does re-importing a module in an imported module actually decreases performance? I'm using math
to demonstrate but the module I'm importing actually takes some time to import (nltk
)
Upvotes: 2
Views: 1810
Reputation: 43024
I'll answer your last question. Python does the work of importing only once, the first time it is imported. It's cached internally. After that, if another module imports the same module, it's pulled quickly from the cache. So there is no performance hit importing multiple times.
Python is smarter than you think. Just write your code in the obvious way.
Upvotes: 8