[Python-ideas] Replacing the if __name__ == "__main__" idiom (was Re: making a module callable)
Ron Adam
ron3200 at gmail.com
Mon Nov 25 16:35:46 CET 2013
On 11/25/2013 09:15 AM, Chris Angelico wrote:
> On Tue, Nov 26, 2013 at 1:55 AM, Ron Adam <ron3200 at gmail.com> wrote:
>> But when there is only *one* of something, and you aren't manipulating the
>> parts, then "is" should be ok. __name__ would be bound directly to
>> __main__'s string object, so "is" or "==" should always work for that case.
>
> Really? Is this something that's guaranteed? I know the CPython
> compiler will optimize a lot of constants, but can you really be sure
> that this is safe?
It seems to me, that you can't do this ...
if __main__ is "__main__":
That depends on the compiler to optimise that case so they are the same object.
But in this case...
__main__ = "__main__"
__name__ = __main__
assert __main__ is __name__
That should always work. I would think it was a bug if it didn't.
Cheers,
Ron
More information about the Python-ideas
mailing list