__main__ vs official module name: distinct module instances

Cameron Simpson cs at zip.com.au
Mon Aug 3 02:59:41 CEST 2015

On 02Aug2015 18:18, Chris Angelico <rosuav at gmail.com> wrote:
>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?

To my eyes, badly, which IMO strengthens my case for addressing the situation 
in the interpreter instead of requiring increasingly complex gyrations on the 
part of every programmer on the planet:-)

Cameron Simpson <cs at zip.com.au>

The CBR and ZXR should come with a warning sticker that says 'You are not
Mick Doohan, do NOT be a prat'  - UK's _BIKE_ magazine

More information about the Python-list mailing list