Import a module from a specific file path (was: PyWart: "Python's import statement and the history of external dependencies")

Chris Angelico rosuav at gmail.com
Fri Nov 21 21:32:09 EST 2014


On Sat, Nov 22, 2014 at 11:37 AM, Ben Finney <ben+python at benfinney.id.au> wrote:
> I don't think I'd ever want to specify an absolute file path for the
> module. But it would make my Python life immeasurably better if I could
> specify *relative* file paths for importing a module.
>
> Allowing relative paths makes this portable, so long as the
> application's relative tree structure is maintained.
>
> Maybe you can suggest a better portable method to do this today in
> Python.

Ah, didn't think of relative paths. Yes, I can see that'd be both more
useful and less problematic.

What you suggest looks very much like you're running something from a
package, though.

> * The program ‘fooprog’ and the module ‘beans.py’ are in a sensible
>   directory structure::
>
>     foo-proj-1.0/
>         foo/
>             __init__.py
>             fooprog
>             bar/
>                 __init__.py
>                 beans.py
>         tests/
>             __init__.py
>             test_fooprog.py
>             test_bar.py

So can you simply:

$ python -m foo.fooprog

? (or 'python3', either way)

ChrisA



More information about the Python-list mailing list