python3相对路径导入代码_10.3 使用相对路径名导入包中子模块

讨论¶

Inside packages, imports involving modules in the same package can either use fully specified absolute names or a relative imports using the syntax shown. For example:

# mypackage/A/spam.py

from mypackage.A import grok # OK

from . import grok # OK

import grok # Error (not found)

The downside of using an absolute name, such as mypackage.A, is that it hardcodes the top-level package name into your source code. This, in turn, makes your code more brittle and hard to work with if you ever want to reorganize it. For example, if you ever changed the name of the package, you would have to go through all of your files and fix the source code. Similarly, hardcoded names make it difficult for someone else to move the code around. For example, perhaps someone wants to install two different versions of a package, differentiating them only by name. If relative imports are used, it would all work fine, whereas everything would break with absolute names.

The . and .. syntax on the import statement might look funny, but think of it as specifying a directory name. . means look in the current directory and ..B means look in the ../B directory. This syntax only works with the from form of import. For example:

from . import grok # OK

import .grok # ERROR

Although it looks like you could navigate the filesystem using a relative import, they are not allowed to escape the directory in which a package is defined. That is, combinations of dotted name patterns that would cause an import to occur from a non-package directory cause an error.

Finally, it should be noted that relative imports only work for modules that are located inside a proper package. In particular, they do not work inside simple modules located at the top level of scripts. They also won’t work if parts of a package are executed directly as a script. For example:

% python3 mypackage/A/spam.py # Relative imports fail

On the other hand, if you execute the preceding script using the -m option to Python, the relative imports will work properly. For example:

% python3 -m mypackage.A.spam # Relative imports work

For more background on relative package imports, see PEP 328 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值