About __main__

I think most Python programmers have written it a thousand times:

if __name__ == '__main__':
    #some code

I also assume you know what the result is of the following code:

class test(object):

print test.__name__

So lets assume the __name__ variable contains the current class name, what would the __main__ class be? It’s the invisible main class of course! But there’s something strange going on:

print test
#<class '__main__.test'>

print __main__
#NameError: name '__main__' is not defined

So… the test function is a member of __main__, but main itself does not exist? Strange… When I was frustrated by this I experimented some, lets check the following piece of code:

import __main__

print __main__
#<module '__main__' (built-in)> 

print dir(__main__)
#['__builtins__', '__doc__', '__main__', '__name__', 'test']

__main__.test2 = 'Hello world!!!'
print test2
#Hello world!!!

Isn’t that amazing? We imported __main__, saw it had the test class assigned to it, we assigned a new variable and saw the module scope updated!

This might sound quite pointless, but you can do a lot of dirty tricks with it, for example assign variables by strings:

name = raw_input('Enter a variable name: ')
setattr(__main__, name, 'Dirty trick')
print dir(__main__)
#['__builtins__', '__doc__', '__main__', '__name__', 'test', 'test2', '<your input here>']

This method is used in my xhtml generator to assign partitial functions for xhtml tags to the module scope(to have a(href=”test”) instead of SomeClass.a(href=”test”) or even SomeClass.html(‘a’, href=”test”).


My blog has moved!

My blog has permanently moved to a self hosted Wordpress at http://pepijndevos.nl

This blog will stay around for accidental search engine visitors.


This is me

Blog Stats

  • 22,233 hits


%d bloggers like this: