Solved, thanks!
Let's say I have a self-written module located under C:\\mymodules\\general
which contains the files foo.py
and __init__.py
.
Now I want to import the function bar()
, which is located inside foo.py
, into a script in a completely different place.
Why is this not working?
import sys
sys.path.append(r"C:\mymodules")
from general import foo
foo.bar()
I get ImportError: cannot import name 'foo'
The same if I add C:\\mymodules\\general
to the path, instead.
Alternatively, I have also tried
import sys
sys.path.append(r"C:\mymodules")
import general.foo
foo.bar()
Here, I get ModuleNotFoundError: No module named 'general.foo'; 'general' is not a package
ModuleNotFoundError: No module named 'general.foo'; 'general' is not a package
.
Why would general not be a package? I thought the requirement was "contains an __init__.py
" (and the module I want to import, of course)?
This is all Python3, using PyDev in Eclipse under Windows7.
Can anyone tell me what's wrong and how to do it instead?
Edit: the file is, indeed, already called __init__.py
, so that is not the problem.
__init__.py
already contains the line
__all__ = ["foo"]
Edit 2: Weirdly enough, the following works:
import sys
sys.path.append(r"C:\mymodules")
from general import *
bar()
I really don't want to do import *
, though. Surely there must be a cleaner way?
Edit 3: When I run it from IDLE, it works! (The first code, that is.) But in Eclipse PyDev, I still get the same error. Why?
Ah! Solution found! (see answer below, to close this).
When using init
file, it has to be with underscores as Robin Zigmond says.
__init__.py
if that doesn't work for you, you may try writing in the init
file
from foo import bar
or
from foo.py import *
Solution found. headdesk
In PyDev's Pythonpath (configured for the whole workspace), I had another package that contains a module called general.py
. The interpreter found this before it got to my package general
, so the message general is not a package
referred to the module of the same name.
That should teach me to use separate workspaces when I do need to reuse existing names. And ideally, not to use the same name for different things, anyway.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.