__main__ vs official module name: distinct module instances

Chris Angelico rosuav at gmail.com
Sun Aug 2 10:18:36 CEST 2015


On Sun, Aug 2, 2015 at 6:16 PM, Chris Angelico <rosuav at gmail.com> wrote:
> On Sun, Aug 2, 2015 at 5:41 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> * if you don't wish to do that, you're screwed, and I think that the
>>   best you can do is program defensively by detecting the problem
>>   after the event and bailing out:
>>
>>   # untested
>>   import __main__
>>   import myactualfilename
>>   if os.path.samefile(__main__.__path__, myactualfilename.__path__):
>>       raise RuntimeError
>
> Not sure what __path__ is here, as most of the things in my
> sys.modules don't have it; do you mean __file__? In theory, it should
> be possible to skim across sys.modules, looking for a match against
> __main__, and raising RuntimeError if any is found.

Oops, premature send.

*In theory* it should be possible to do the above, but whichever
attribute you look for, some modules may not have it. How does this
play with, for instance, zipimport, where there's no actual file name
for the module?

ChrisA


More information about the Python-list mailing list