Python programs and relative imports

Chris Angelico rosuav at gmail.com
Fri Apr 8 14:04:01 EDT 2016


On Sat, Apr 9, 2016 at 3:50 AM, Rob Gaddi
<rgaddi at highlandtechnology.invalid> wrote:
> Sort of.  If I've got a directory full of files (in a package)
> that I'm working on, the relative import semantics change based on
> whether I'm one directory up and importing the package or in the same
> directory and importing the files locally.  That is to say if I've got:
>
> pkg/
>   __init__.py
>   a.py
>   usedbya.py
>
> then there is no single syntax I can use in a.py that allows me to both
> sit in the pkg directory at the shell and poke at things and import pkg
> from the higher level.
>
> If the 'from . import usedbya' syntax were always available, then it
> would work the same in either context.  And if as I refactored things,
> as they moved in and out of packages, it would all still "just work" for
> files that haven't moved relative to one another.

Ah, I see what you mean. You're working inside an actual package here.
So you can "cd ..; python3 -m pkg.a", or you can "python3 a.py", but
not both.

The simplest fix for that would be to allow "python3 -m .a" to mean
"current directory is a package". I don't think there's currently a
way to spell that, but it ought to be completely backward compatible.
You could raise this on python-ideas and see what people say.

ChrisA



More information about the Python-list mailing list