define module in non-standard location?

S

Shane

Normally if one has a code set under a directory "top_level" like
this:

top_level:
__main__.py
a
__init__.py
b
__init__.py

then this directory structure is naturally satisfies this line in
__main__.py:
import a.b

But support, for some stupid reason --- say a.b is user defined code
--- that I want
to locate modules a and a.b somewhere else under another directory
"other_top_level".
What would the line "import a.b" in __main__,py be replaced by?

Thank you
 
S

Steven D'Aprano

Normally if one has a code set under a directory "top_level" like this:

top_level:
__main__.py
a
__init__.py
b
__init__.py

then this directory structure is naturally satisfies this line in
__main__.py:


But support, for some stupid reason --- say a.b is user defined code ---
that I want
to locate modules a and a.b somewhere else under another directory
"other_top_level".

You mean like this?

top_level/
__main__.py
other_top_level/
a/
__init__.py
b/
__init__.py



What would the line "import a.b" in __main__,py be replaced by?


Make sure other_top_level is in your PYTHONPATH, and then just use
"import a.b" as before.


Either use your shell to do something like this:

export PYTHONPATH=other_top_level:$PYTHONPATH

(that's using bash syntax, other shells may need something different), or
in __main__.py do this:

import sys
sys.path.append(other_top_level)
 
S

Shane

You mean like this?

top_level/
    __main__.py
other_top_level/
    a/
        __init__.py
        b/
            __init__.py


Make sure other_top_level is in your PYTHONPATH, and then just use
"import a.b" as before.

Either use your shell to do something like this:

export PYTHONPATH=other_top_level:$PYTHONPATH

(that's using bash syntax, other shells may need something different), or
in __main__.py do this:

import sys
sys.path.append(other_top_level)

Cheers. Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top