A mistake which almost went me mad

Chris Angelico rosuav at gmail.com
Mon Mar 7 11:40:31 EST 2016


On Tue, Mar 8, 2016 at 3:19 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Thu, Mar 3, 2016 at 11:50 AM, Tim Chase
> <python.list at tim.thechases.com> wrote:
>> I think that relative imports should ameliorate this, as I usually
>> hit it when I'm using smtplib which in turn imports "email" (and, in
>> 2.x when it found my local email.py would crash and burn). If it used
>> a relative import that forced it to find the one in the stdlib, it
>> should(?) prevent it from finding my local version first.
>
> Relative imports only work inside packages. You can't use a relative
> import to import one top-level module from another.
>
> Besides, the relative import doesn't help to disambiguate in this
> case. The absolute path of the stdlib email module is "email". The
> absolute path of the module in your CWD is also "email". Why should a
> relative import prefer one over the other? So I would think that even
> if it worked, it would still just end up importing the first one it
> finds on your sys.path.

So the solution is to treat the current directory as a pseudo-package.
It'd be a backward-incompatible change, so it would need to be
explicitly invoked. Something like:

python3 -p somefile.py

which would pretend to create an __init__.py in the current directory,
change to the parent, and "from dirname import somefile". I mentioned
this one time before, but it got kinda missed; I think I'll reraise it
on python-ideas. It's a protection on par with not having the current
directory in $PATH.

ChrisA



More information about the Python-list mailing list