In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to understand the cross-reference between Python modules". The content in the article is simple and clear, and it is easy to learn and understand. please follow the editor's train of thought to study and learn "how to understand the cross-reference between Python modules".
The following two errors occurred during a certain operation:
Error 1: ModuleNotFoundError: No module named'_ main__.src_test1';'_ main__' is not a package error 2: ImportError: attempted relative import with no known parent package
So based on these two error reports to explore the problem of mutual reference between modules in python3, let's analyze them one by one, please read it patiently.
OK, let's construct the first error first, and the test code is structured as follows:
| |-test_main.py |-src |-_ _ init__.py |-src_test1.py |-src_test2.py |
Src_test2.py code
Class Test2 (object): def foo (self): print ('I am foo')
Src_test1.py code, referencing Test2 module
From .src _ test2 import Test2def fun1 (): T2 = Test2 () t2.foo () if _ _ name__ = = "_ _ main__": fun1 ()
Run src_test1.py error "No module named'_ main__.src_test1';'_ _ main__' is not a package" at this time
The cause of the problem:
The main reason is that when referencing the src_test2 module, the relative path is used, which is translated into ". /" in the import syntax, that is, under the current directory, it is no problem to understand in this way, so why did you report an error?
From PEP 328, we found an introduction to the relative imports (relative reference)
In a popular way, it means that the module running at the entrance of your program defaults to the main module, and its name is' main', 'and then the dot (.) in the import of this module. Replace it with'_ _ main__', then .src _ test2 becomes _ _ main__.src_test2, so of course you can't find this module.
Solution:
Therefore, the recommended practice is to create a reference module test_main.py in the src peer directory (why not create it in the src directory until the next error is reported later), and reference the src_test1 module as follows:
From src.src_test1 import fun1if _ _ name__ = "_ _ main__": fun1 ()
Then why can it be carried out in this way, and what is the principle? I understand it this way (welcome to correct): when test_main executes, he is treated as the root directory, so the src.src_test1 he refers to is the absolute path, so the reference can't be wrong anywhere. When his name='main', executes src_test1, notice that the name of test1 is src.src_test1, then the relative path is used in test1, and the search logic is to find the parent node (src directory) first. Then find the src_test2 under the parent node, so you can find it successfully, Bingo!
Supplementary evidence:
By constructing an example, you can understand that the above execution directory is the root directory. Modify test1 to refer to test_main:
From.. Import test_main error: ValueError: attempted relative import beyond top-level package
OK, then continue to construct the second error:
As mentioned above, the solution to the main problem is to create a module to call a module that uses a relative path, so why can't I create this file in the same directory to call it? Let's test the code:
Create a test_src.py file and change the code structure as follows:
| |-test_main.py |-src |-_ _ init__.py |-src_test1.py |-src_test2.pys |-test_src.py |
Test_src Code:
From src_test1 import fun1if _ _ name__ = "_ _ main__": fun1 ()
Execute error report: ImportError: attempted relative import with no known parent package
The cause of the problem:
When executing test_src, according to the above understanding, the directory where the execution file is located is the root directory, so when referencing test1, it should be noted that the name attribute of test1 is no longer src.src_test1, because the program is not aware of the existence of src, its absolute path is src_test1, and the relative path lookup test2 is referenced again. In the same step, you need to find the parent node first, and at this time he is the root node. There is no parent node, so the error "no known parent package" was reported.
Solution:
At this time, in order to avoid conflicts between the parent nodes, you can remove the relative references from the introduction in test1.
From .src _ test2 import Test2-> from src_test2 import Test2 continues to drill down:
So how did the compiler find this module using relative and absolute paths?
When executing import, there is an introduction order, that is, priority is to find whether there is this file in the execution directory, if not, then look under the lib library, if not, then look for the path in sys.path, if no more, report an error.
So whether it is the current directory or the directory in sys.path, you can find the src_test2 module and compile it successfully.
Extra:
After solving the above problems, no matter which way we use, when we debug the code, we debug a single file, but at this time the root directory is wrong, and the import method has to be changed, which is very troublesome to execute, so another way (there is a better way to welcome comments) is recommended here, using the method of sys.path.append ().
Import sys,ossys.path.append (os.getcwd ()) from src.src_test2 import Test2
Using append, put the root directory of the program file into sys.path, and then reference the absolute path, this way, no matter using the first or second execution mode above can be called, you can also compile the test1 file separately, without modifying the import path, it is also a relatively safe way. But the disadvantage is that if you change a package name, you need to change all the references, which is a lot of work, so take measures according to local conditions.
Thank you for reading, the above is the content of "how to understand the problem of cross-reference between Python modules". After the study of this article, I believe you have a deeper understanding of how to understand the problem of cross-reference between Python modules, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.