PEP 328, absolute/relative import

Bengt Richter bokr at oz.net
Thu Aug 11 18:20:53 EDT 2005


On Thu, 11 Aug 2005 14:55:57 -0400, Peter Hansen <peter at engcorp.com> wrote:

>Bengt Richter wrote:
>> Will/should an __init__.py in the current directory be required,
>> to control what happens (and lessen the probability of accidental
>> collision from a random working directory)?
>
>I don't think so.  That would simply shift the possibility of mysterious 
>behaviour from the issue of colliding file names to the issue of whether 
>an __init__.py exists somewhere.  Shouldn't one be allowed to treat 
>files in the current directory as regular Python scripts even if the 
>that directory contains an __init__.py so that it can be found as a 
>Python package *in other contexts*?
>
Hm. When you say "regular scripts," do you mean as in

   some_shell_prompt> python script.py

or do you mean in an interactive session, as in

   >>> import script

?
I think the first should be unaffected by __init__.py, but
the second is slated to become an absolute import (IIUC) that
will search the python path. Packages have to have __init__.py
in order to be searched in dotted paths, so why shouldn't the
current-working-directory-as-package-on-the-path also?

IOW, the mysterious shadowing could only happen if you
were mucking around in one of your path directories as cwd.
An ordinary directory as cwd would not be searched first
unless you gave it that priority with an __init__.py AND
being there as cwd. You could do that for convenience
without making it part of your normal path (except by
being there as cwd, which you would only do for that project
and desired shadowing effect).

Then if you really wanted a one-shot override, in an
un-marked-with-__init__.py directory, maybe

    >>> from . import script

could possibly allow the cwd import without __init__.py
since the cwd at interpreter startup is probably a reasonable
interpretation of '.' in that case.

... just thinking out loud ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list