Python import modules in another file

為{幸葍}努か 提交于 2019-12-04 09:11:46

Yeah I guess there is a more elegant way of doing this which will save redundant line of code. Suppose you want to import some modules math, time, numpy(say), then you can create a file importing_modules(say) and import the various modules as from module_name import *, So the importing_modules.py may look something like this:

importing_modules.py

from math import *
from numpy import *
from time import *

main.py

from importing_modules import *
#Now you can call the methods of that module directly
print sqrt(25) #Now we can call sqrt() directly in place of math.sqrt() or importing_modules.math.sqrt().
Narpar1217

The other answer shows how what you want is (sort of) possible, but didn't address your second question about good practice.

Using import * is almost invariably considered bad practice. See "Why is import * bad?" and "Importing * from a package" from the docs.

Remember from PEP 20 that explicit is better than implicit. With explicit, specific imports (e.g. from math import sqrt) in every module, there is never confusion about from where a name came, your module's namespace includes only what it needs, and bugs are prevented.

The downside of having to write a couple import statements per module does not outweigh the potential problems introduced by trying to get around writing them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!