drpexe
drpexe

Reputation: 461

import python module from another package

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.

Upvotes: 4

Views: 3788

Answers (3)

Pawel Miech
Pawel Miech

Reputation: 7822

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.

Upvotes: 1

jfs
jfs

Reputation: 414875

If 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.

Upvotes: 0

Alex Kroll
Alex Kroll

Reputation: 481

Put the __init__.py next to module.py.

More information http://docs.python.org/3/tutorial/modules.html?highlight=packages#packages

Upvotes: 0

Related Questions