[Python-ideas] Prevent importing yourself?
Ned Batchelder
ned at nedbatchelder.com
Sat Jan 30 06:19:35 EST 2016
On 1/30/16 4:30 AM, Nick Coghlan wrote:
> 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).
I thought about the indirect case, and for the errors I'm trying to make
clearer, the direct case is plenty.
While we're at it though, re-importing __main__ is a separate kind of
behavior that is often a problem, since it means you'll have the same
classes defined twice.
--Ned.
> Cheers,
> Nick.
>
More information about the Python-ideas
mailing list