Question about imports and packages

Ben Finney ben+python at benfinney.id.au
Wed May 25 00:39:56 EDT 2016


Gerald Britton <gerald.britton at gmail.com> writes:

> On Wed, 25 May 2016 10:00 am, Steven D'Aprano wrote:
> >The problem is that you are running the Python script from *inside*
> >the package. That means, as far as the script can see, there is no
> >longer a package visible -- it cannot see its own outside from the
> >inside.
>
> Thanks for the explanation, Steven. I'm just having trouble
> reconciling this with the docs which seems to imply that an intra
> package import should work from inside the package.

The relative import will work fine inside a package.

The key difference is in *whether* your module is inside that package at
run time.

You have hit upon one of my primary complaints about Python. It makes
this normal mode of running a script::

    python3 ./foo.py

not work properly, because Python in that case has no idea in which
package the module belongs. So it can't import other modules relative to
the current directory.

What the Python import system expects you to do is::

    cd ../
    python3 -m fnord.foo

To me, that makes Python at a *severe* handicap as a simple-to-use
scripting language.

But apparently “address a module by filesystem path” is severely
deprecated in Python. From that follows a lot of problems, such as this
one.


For more on traps with Python's import system, see
<URL:http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html>

-- 
 \       “I cannot be angry at God, in whom I do not believe.” —Simone |
  `\                                                       De Beauvoir |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list