Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

python - Libraries imported in one .py doesnt work for imported functions of anothers .py

Hope you can help me on this, here is the problem: I'm working in "x.py" in which I have imported a lot of functions from another file named "functions.py".

Also, I have some specific functions in other files (s1.py,s2.py lets say...), which I also called in my x.py.

The problem comes when I try to use a function or library from functions.py in order to help me with those specifics files where I have other functions (s1.py, s2.py). They just simply dont recognize the libraries which I already imported... ???

Work around I've been using: declare the libraries needed directly in s1.py and s2.py, but I don't like it to much, it seems like I'm duplicating that code.

Is there any way to get my s1.py and s2.py to recognize the imported libraries in x.py???

question from:https://stackoverflow.com/questions/65946598/libraries-imported-in-one-py-doesnt-work-for-imported-functions-of-anothers-py

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Importing a module does not import all its imports by default. You do need to import functions in s1 and s2 even if you are already doing import x.

Or alternatively, you could do from x import functions inside s1 and s2. But personally I'm not sure if I would ever do that - it obfuscates things a bit, and one might say that code duplication is not a thing in the case of imports. Maybe it would make sense on a conceptual level: we import functions via x because the functions are specific to x. But in such case I would make x a package and put functions in that package (in which case the import statement would incidentally look the same). But if functions is not specific to x, i.e. it is expected to be useful for various modules unrelated to x, then don't import it via x.

If you're concerned about the performance impact of multiple imports, this explains that there is none.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...