Home  >  Q&A  >  body text

[Python Newbie] Asked about importing nested packages

First look at the directory structure of my package:

The name of the outermost package is Msgnew, which contains an init file. There is a module called get and a sub-package called Msg. Enter the Msg sub-package and you can see that there is also an init file and there are 2 modules, one is called Sendmsg and the other is called Receivemsg module

I now want to import the Sendmsg module in the sub-package and use one of the functions
By the way, let me introduce the Sendmsg module, which is actually three functions, as shown in the figure:

The code for the import process is as follows:

# -*- coding:gb2312 -*-
# 代码1
from Msgnew import Msg
Msg.Sendmsg.test1()

# 代码2
#from Msgnew.Msg import Sendmsg
#Sendmsg.test1()

Here are code 1 and code 2
The execution results of code 1 are as follows:

Then comment out code 1 and then execute code 2. The result is as follows:

I don’t understand this very much,


Are the two pieces of code in the red box not equivalent?
In my opinion, these two should mean the same thing. Why is one wrong and the other right?

phpcn_u1582phpcn_u15822667 days ago740

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-06-30 09:56:57

    Although they are all sub-modules, their implementation logic is actually different, which leads to the fact that the final import must be a Python file, not a module directory, so the second code The import Sendmsg part actually introduces this Python file, and the previous from Msgnew.Msg tells the parser where to find the Sendmsg file.

    reply
    0
  • 某草草

    某草草2017-06-30 09:56:57

    I know where the problem I encountered lies.
    When importing is not a module but a package, if you want to directly import the modules inside together, you must write in the init file of the package:

    __all__ = ["Sendmsg","Receivemsg"]
    
    from . import Sendmsg
    from . import Receivemsg

    As shown in the picture:

    The next time you execute it, it will be successful!

    reply
    0
  • Cancelreply