[Beginer Question] I heard about python needing somesort of_VariableName_ boiler plate?

Terry Reedy tjreedy at udel.edu
Mon Nov 1 15:42:52 EDT 2010


On 11/1/2010 2:18 PM, bradenf at hotmail.com wrote:
> Sorry that is what I mean. What is it for?
> Sent wirelessly from my BlackBerry.

Does it require you to toppost? Understanding the above requires one to 
guess what 'that' forward references.

> Perhaps the OP means:
>
>       if __name__ == "__main__":

I presume that this is the 'that' which you forward-referenced. If so...

Python reserves names of the form __xyz__ for itself. This is 
intentionally a bit awkward so as to stand out in code and not conflict 
with names a programmer might choose. This form is used for names that 
programmers *mostly* do not need to use. The system names that we do 
need to use constantly, like 'None', 'def', and 'int' have normal 
spellings. These are easy to type, but may conflict with a name that a 
programmer might be using.

Every module has a name stored in its __name__ attribute. The the 
interpreter starts, it names the top level module, which is run directly 
instead of being imported, as '__main__'.  When a module is run 
indirectly, by being imported, its name is what you expect from the docs 
or from the name of its file.

So:
1. a module can have one of two runtime names (as defined by it __name__ 
attribute): '__main__' or its proper name.
2. a module's runtime name depends on whether it is run directly or 
imported.
3. a module can therefor  tell how it is being run; this is usually done 
with "if __name__ == '__main__'.
4. a module can change its behavior depending on how it is run by 
putting code in the body of the conditional statement. Such a 
conditional statement is entirely OPTIONAL.

There are two things people do in such a body.
a. If the module is meant either imported or run as a useful standalone 
program (such as the stdlib trace module), check for arguments in 
sys.argv, do some useful work, and report.
b. If the module is normally only meant to be imported, run a test.

If a module is only meant to run as a program, or if it is only meant to 
be imported and all its tests are in a separate file, there there is no 
need for the conditional statement.

-- 
Terry Jan Reedy




More information about the Python-list mailing list