python包导入细节_在Python中导入深度嵌套的模块

Consider the following case in Python 3.6:

basepackage

|---__init__.py

|---package

|---__init__.py

|---subpackage

|---__init__.py

|---module.py

Important detail: inside basepackage.package.__init__.py there's:

from basepackage.package.subpackage.module import AClass as AliasedClass

Now, let's say inside basepackage.package.subpackage.module.py we want to use:

import basepackage.package.subpackage.module as aliased_module [1]

The result is:

AttributeError: module 'basepackage' has no attribute 'package'

with a stack trace listing following culprit statements (in the below order):

from basepackage.package.subpackage.module import AClass as AliasedClass

import basepackage.package.subpackage.module as aliased_module

But if instead of [1] one'd like to use:

from basepackage.package.subpackage import module as aliased_module [2]

then everything works.

How is [1] so much different than [2] that the former results in an error and the latter not?

解决方案

For the first option (import basepackage.package.subpackage.module as aliased_module) to work, these conditions have to be met:

basepackage/__init__.py has to contain a line similar to from . import package (the name package has to be defined inside this basepackage/__init__.py file)

basepackage/package/__init__.py has to contain a line similar to from . import subpackage

basepackage/package/subpackage/__init__.py has to contain a line similar to from . import module

Note: the import statements inside the __init__.py files can also be absolute instead of relative paths.

For the second option (from basepackage.package.subpackage import module as aliased_module), it is enough if there are empty __init__.py files at each level, as long as these __init__.py files exist.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值