I have a script with the following structure
./
/foo
__init__.py
/bar
__init__.py
module.py
I want to use module.py both on foo and bar package, but i can't find a way to import it!
I can put the module inside both packages, but if I need to make any alteration I would have to do it on both.
3 Answers 3
This is actually somewhat tricky, assuming we have structure like this:
├── bar
│ ├── __init__.py
│ └── some_bar.py
├── foo
│ ├── __init__.py
│ └── some_foo.py
└── something.py
the correct way to get objects from something.py in some_foo.py is by adding:
# foo/some_foo.py
from something import some_module
and then running some_foo from top level directory as a module, with -m option like so:
python -m foo.some_foo
add some print statements to something.py to test it, if everything goes right you should see some output from something.py after running some_foo. Remember you need to run some_foo from top level, not from foo directory.
2 Comments
__init__.py along side a possibly top-level module something.py? Why would you recommend import * in this case? Don't create the __init__.py file and don't use import * here.something.py is not a package. from something import some_module might be misleading (technically, you could make something.py into a package programmatically but usually Python packages created as directories (like foo, bar in this case)).Put the __init__.py next to module.py.
More information http://docs.python.org/3/tutorial/modules.html?highlight=packages#packages
1 Comment
__init__.py file if the module is outside of any packageIf import foo works then import module should work in your case too.
If you need to use from toplevel import foo to import foo then you could use from toplevel import module to import module.
5 Comments
from foo import test foo\test.py: from . import module >python module.py - > ImportError: cannot import name module No way to use from toplevel import module except PYTHONPATH magic?__init__.py only needs for packages.module.py is not inside foo. Why do you think from . import module would have worked? Use import module instead. Don't put info in the comment, update your question insteadmodule from foo\test.py with import from syntax?foo is toplevel in your case. It means that you should use import module.
import module? Ifmodule.py's directory is on the path, that should work. If it's not on the path, then you couldn't have imported your packages either.