While trying to do something similar to what's in the ActiveState recipe titled Constants in Python by Alex Martelli, I ran into the unexpected side-effect (in Python 2.7) that assigning a class instance to an entry in sys.modules
has -- namely that doing so apparently changes the value of __name__
to None
as illustrated in the following code fragment (which breaks part of the code in the recipe):
class _test(object): pass
import sys
print '# __name__: %r' % __name__
# __name__: '__main__'
sys.modules[__name__] = _test()
print '# __name__: %r' % __name__
# __name__: None
if __name__ == '__main__': # never executes...
import test
print "done"
I'd like to understand why this is happening. I don't believe it was that way in Python 2.6 and earlier versions since I have some older code where apparently the if __name__ == '__main__':
conditional worked as expected following the assignment (but no longer does).
FWIW, I also noticed that the name _test
is getting rebound from a class object to None
, too, after the assignment. It seems odd to me that they're being rebound to None
rather than disappearing altogether...
Update:
I'd like to add that any workarounds for achieving the effect of if __name__ == '__main__':
, given what happens would be greatly appreciated. TIA!
__dict__
. – Kirkwall