Python Import Class With Same Name as Directory [duplicate]

无人久伴 提交于 2019-11-29 09:36:18

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.

I'm pretty sure this is not something you should do, but you can force Python to import specific file as a module using imp:

import imp

with open("foo.py") as source:
    foo = imp.load_module("foo", source, "./", ('', '', imp.PY_SOURCE))

now you can do:

gaz_instance = foo.gaz()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!