[Python-ideas] Prevent importing yourself?

Nick Coghlan ncoghlan at gmail.com
Sun Jan 31 01:44:53 EST 2016


On 30 January 2016 at 23:20, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
> On 30 January 2016 at 11:57, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> On 30 January 2016 at 21:19, Ned Batchelder <ned at nedbatchelder.com> wrote:
>>> On 1/30/16 4:30 AM, Nick Coghlan wrote:
>>>> 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.
>>
>> In that case, the only problem I see off the top of my head with
>> emitting a warning for direct self-imports is that it would rely on
>> import system behaviour we're currently trying to reduce/minimise: the
>> import machinery needing visibility into the globals for the module
>> initiating the import.
>>
>> It's also possible that by the time we get hold of the __spec__ for
>> the module being imported, we've already dropped our reference to the
>> importing module's globals, so we can't check against __file__ any
>> more. However, I'd need to go read the code to remember how quickly we
>> get to extracting just the globals of potential interest.
>
> Maybe this is because I don't really understand how the import
> machinery works but I would say that if I run
>
>     $ python random.py
>
> Then the interpreter should be able to know that __main__ is called
> "random" and know the path to that file. It should also be evident if
> '' is at the front of sys.path then "import random" is going to import
> that same module. Why is it difficult to detect that case?

Yes, this is the case I originally said we could definitely detect.
The case I don't know if we can readily detect is the one where a
module *other than __main__* is imported a second time under a
different name. However, I'm not sure that latter capability would be
at all useful, so it probably doesn't matter whether or not it's
feasible.

Cheers,
Nick.

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


More information about the Python-ideas mailing list