Python programs and relative imports

Ian Kelly ian.g.kelly at gmail.com
Fri Apr 8 14:26:52 EDT 2016


On Fri, Apr 8, 2016 at 11: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.

Not necessarily. Inside the package, 'from . import usedbya' is
effectively equivalent to 'import pkg.usedbya as usedbya'. Without the
package, all of these modules are at the top level, and 'from . import
usedbya' would conceptually be equivalent to 'import usedbya'. But
there's no guarantee that the 'usedbya' module at the top level of the
module tree is the same 'usedbya.py' file in the current directory; it
could be shadowed by some other module. Whereas with the package, the
packaging ensures that you'll get the module expect.



More information about the Python-list mailing list