简体   繁体   中英

Avoid importing a module in an imported module

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 )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM