[Tutor] __name__=='__main__'

Robert Sjoblom robert.sjoblom at gmail.com
Tue Feb 21 02:52:05 CET 2012


> I am having some trouble understanding how to use __name__== '__main__'. Can
> you please give me some insight?

if __name__ == '__main__': allows you to specify code that will only
be run if you run the actual script it's in; anything in the if block
won't be run if you import the module.

>Also, to use this, it needs to be within a
> function? Do you typically just throw it in your very last function or
> create a separate function just for this? I at first put it outside and
> after all my functions but got the error below and then put it inside my
> last function and the program ran. (side note, I have an error in my return
> for MultiplyText that I am still trying to work out, so you can ignore that
> part).

No, it doesn't have to be in a function, but if you wish you can have
it in a function main() or similar. The reason why you're getting an
error isn't because it's outside a function, it's because you're not
using the correct name:
> Traceback (most recent call last):
>   File "C:/Python27/Homework/Homework5_1.py", line 24, in <module>
>     if __name == '__main__':
> NameError: name '__name' is not defined
As it says in the traceback, '__name' is not defined. It should be '__name__'.

> def GetUserInput():
>     '''Get S & multiplier. Test multiplier.isdigit(). Call
> MultiplyText(text, multiplier)'''
>     while True:
>         text = raw_input('Enter some text: ')
>         multiplier = raw_input('Enter a multiplier: ')
>         try:
>             multiplier.isdigit()
>             break
>         except ValueError:
>             continue
>     new_text = MultiplyText(text, multiplier)
>     return new_text
>
>     if __name == '__main__':
>         print GetUserInput()

You shouldn't have the "if '__name__' " block in any of your functions
(except possibly main()), it looks bad. I'm unsure if it'll affect
things when you import functions, but on the off-chance that it does,
you shouldn't do it.

A short example:
critter.py:
class Critter(object):
    """A virtual pet."""
    def __init__(self):
        print("A new critter has been born!")

    def talk(self):
        print("Hi, I'm an instance of class Critter.")

if __name__ == '__main__':
    crit1 = Critter()
    crit2 = Critter()

    crit1.talk()
    crit2.talk()

If I run this from critter.py, I will get the following output:
A new critter has been born!
A new critter has been born!
Hi, I'm an instance of class Critter.
Hi, I'm an instance of class Critter.

However, if I create a critter_import.py and inside it import my Critter class:

from critter import Critter

if __name__ == '__main__':
    print("This is critter_import.py")

The output will only be:
This is critter_import.py

If I subsequently create critters in critter_import.py, I will indeed
get the output that we see in critter.py, but that's because of class
behaviour and not because the if '__name__' block in critter.py
executes.

I might have made a mess of explaining things. In short: if '__name__'
== '__main__': only happens if you run the actual file, whereas it
won't happen if you import things from the file.
-- 
best regards,
Robert S.


More information about the Tutor mailing list