[Import-SIG] Revising PEP 395 to handle implicit package directories

Paul Moore p.f.moore at gmail.com
Wed Mar 14 00:40:37 CET 2012

On 13 March 2012 22:37, Nick Coghlan <ncoghlan at gmail.com> wrote:
> Interactive prompt:
>    The current working directory appears to be inside a Python
> package. This can cause unexpected Import Errors and other strange
> behaviour. Consider using "os.chdir('<path>')" to move the working
> directory to the parent directory of the package and accessing modules
> under their full name.

This remains the crux of my problem with this issue. Changing the current
directory affects global state. I can *consider* doing so, but I may have
reasons not to want to. The recommendation offers me no option then.

An alternative option might be to set PYTHONPATH, but that's also global
state. (Unix users can do "PYTHONPATH=xxx python" but that's not an option on

Actually, explaining the problem and issues isn't hard:

- Apart from sys.path[0], sys.path is static. You know what's on it (basically
  the stdlib and installed packages, except if you get fancy).
- sys.path[0] is set to the directory containing the executed file, or the
  current directory for interactive use or -m.

The consequences of this may be unexpected, and they may not be what the user
would like, but they aren't obscure, surely? (Nick, feel free to tell me I'm
wrong, and there's a lot more complexity here - but I hope there isn't)

As Nick says, it's possible to detect when the user has a mistaken view of
what's happening and issue a warning, but I don't think the warning needs to
be quite so scary ("strange behaviour"). Something simpler, like the
following, would be better in my view:

"You appear to be trying to import the package containing XXX[1]. But the
Python module path does not include the directory containing that package. You
can add that directory to the module path either by setting PYTHONPATH, or by
changing the current directory (and using python -m if you want to execute a
module in the package)."

[1] either "the current directory" or "the script you are running" as

This has the benefit of explaining the actual problem and its cause, and
giving the user some alternative options to fix it. (The wording could
possibly be improved a bit).

To alleviate the problem of having to alter global state, would it be worth
having an option (like Java's -classpath option) to add sys.path entries for
one invocation of Python (Unix users can do "PYTHONPATH=xxx python", but
that's a bit verbose and not available to Windows users). Something like

    python -P dir1;dir2;dir3 rest_of_args

which works like temporarily adding dir1;dir2;dir3 to the start of PYTHONPATH.
If this was added, the error message could offer using -P as another option.


More information about the Import-SIG mailing list