This question already has an answer here:
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!
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:
now you can do:
The actual problem you are having, using a single import, is due to the packages having the precedence over modules:
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 simpledict
and thus it cannot contain multiple equal keys.In particular, assuming
foo.py
and thefoo
directory are in different directories(and if they aren't you still can't importfoo.py
), when doing:It will load
foo.py
and put the module intosys.modules
, then trying to do: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.