导入同名的python包_Python导入类与目录同名

Lets say I have the following python source file layout:

lib/foo.py

lib/foo/bar.py

and then in my source code:

from foo import gaz

I get an import error:

ImportError: No module named foo

How can I have a .py file and a directory with the same name so I can do the following:

from foo import gaz

from foo.bar import wakawaka

thanks in advance!

解决方案

The actual problem you are having, using a single import, is due to the packages having the precedence over modules:

Note that when using from package import item, the item can be either

a submodule (or subpackage) of the package, or some other name defined

in the package, like a function, class or variable. The import

statement first tests whether the item is defined in the package; if

not, it assumes it is a module and attempts to load it. If it fails to

find it, an ImportError exception is raised.

Anyway I'd strongly suggest to rename the file or the directory since you cannot import more than one module with a given name. The problem occurs because each module/package object is stored into sys.modules, which is a simple dict and thus it cannot contain multiple equal keys.

In particular, assuming foo.py and the foo directory are in different directories(and if they aren't you still can't import foo.py), when doing:

from foo import gaz

It will load foo.py and put the module into sys.modules, then trying to do:

from foo.bar import wakaka

Will fail because the import tries to use the module foo.py instead of the package.

The opposite happens if you first import foo.bar; the imports will use the package instead of the module.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值