[Python-ideas] Prevent importing yourself?

Nick Coghlan ncoghlan at gmail.com
Sat Jan 30 04:30:05 EST 2016


On 30 January 2016 at 08:42, Ned Batchelder <ned at nedbatchelder.com> wrote:
> Hi,
>
> A common question we get in the #python IRC channel is, "I tried importing a
> module, but I get an AttributeError trying to use the things it said it
> provided."  Turns out the beginner named their own file the same as the
> module they were trying to use.
>
> That is, they want to try (for example) the "azure" package.  So they make a
> file called azure.py, and start with "import azure". The import succeeds,
> but it has none of the contents the documentation claims, because they have
> imported themselves.  It's baffling, because they have used the exact
> statements shown in the examples, but it doesn't work.
>
> Could we make this a more obvious failure?  Is there ever a valid reason for
> a file to import itself?  Is this situation detectable in the import
> machinery?

We could potentially detect when __main__ is being reimported under a
different name and issue a user visible warning when it happens, but
we can't readily detect a file importing itself in the general case
(since it may be an indirect circular reference rather than a direct).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list