Did you ever wonder what Python does with all those variables and functions you write in the Maya script editor? No? Well I am going to tell you anyway. I recently refered to the Maya Script Editors Python global scope or main namespace as the main module to a friend. He said that I must have been tired and meant something else, but I didnt and here is why.
Type in and execute the following code into your script editor in a Maya Python tab:
print __name__
Which will print:
__main__
When you print __name__ in a module it will give you the namespace of the module itself. So why did printing __name__ work inside of the Script Editor? Now write a quick function and execute it in the Script Editor:
def test():
"""this function is a test"""
print "test"
Next type and execute the following line:
help(test)
#Result:
Help on function test in module __main__:
test()
testing
Ok so your thinking its just calling it module __main__ its not really a real module is it? Try executing the following:
import __main__ dir(__main__) # Result: ['__builtins__', '__doc__', '__main__', '__name__', '__package__', 'test'] #
You can see that by calling dir on the __main__ module that test has been defined inside of the __main__ module. So Python is adding functions that we write and variables on the fly to this __main__ module. If you import a module it will also go into this list.
import math dir(__main__) # Result: ['__builtins__', '__doc__', '__main__', '__name__', '__package__', 'math', 'test'] #
Every Python program starts with a __main__ module. If we were to make a Python program outside of Maya the first module loaded and executed would become the __main__ module. Some people write a line that states:
if __name__ == "__main__":
print "do special stuff if your the main module"
Python docs state:
http://docs.python.org/library/__main__.html
“This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes — commands read either from standard input, from a script file, or from an interactive prompt. It is this environment in which the idiomatic “conditional script” stanza causes a script to run:”
In the end the __main__ module is not an actual file though, but you could call it the main module.
Have fun,
Ryan
Recent Comments