Learntofish's Blog

A blog about math, physics and computer science

Tutorial: Object Oriented Programming in Python – Part 7

Posted by Ed on December 10, 2011

This is the continuation of the Python OOP tutorial. Last time we addressed modules. Here, I want to talk about a special expression. When reading other people’s modules you may encounter this expression at the end of their module:

if __name__ == "__main__":

Let’s write a module (in other words: a Python file):

# pizza module
def food():
    print("I like pizza!")

print("You have run the pizza module.")

Copy the code and save it in a file pizza.py. Then run the file in the Python-Shell (e.g. in IDLE by pressing F5). The Python-Shell immediately shows the following:

>>> ================================ RESTART ================================
>>> 
You have run the pizza module.

Without having typed anything in the Python-Shell it printed “You have run the pizza module” due to line 5 of pizza.py. This is nice since it signalizes that pizza.py was run. However, there is a twist.

Let’s write another module:

# testM module
from pizza import food

def myProgram():
    food()

Save the code in a file testM.py. Let’s examine the code:
– In line 2 we import the function food() from the module pizza. Notice that in the last tutorial I’ve only mentioned the import of a class. Here we see that we can also import a function.
– In line 4-5 we define a function myProgram(). Line 5 shows that myProgram() just calls the function food() (which should be available because we imported it in line 2).

Run testM.py in the Python-Shell (e.g. by pressing F5 in IDLE) and enter myProgram(). The Python-Shell shows the following:

>>> ================================ RESTART ================================
>>> 
You have run the pizza module.
>>> myProgram()
I like pizza!

Let’s examine the output:
– After entering myProgram() we get the message “I like pizza!” which is what we expected. Recall that myProgram() just calls food() which is responsible for that message.
– But now, here’s the twist: Right after running testM.py the Python-Shell prints “You have run the pizza module.”. This is obviously wrong, since we did not run the pizza module but the testM module.
– The problem is line 5 in pizza.py. Can we prevent line 5 from being executed if we only import the pizza module?

Indeed, there is a possibility. We will change pizza.py a little:

# pizza module edited
def food():
    print("I like pizza!")

if __name__ == "__main__":
    print("You have run the pizza module.")

In line 5 we added the ominous if statement mentioned at the beginning. Save the changes in pizza.py. Then run testM.py in the Python-Shell and type myProgram():

>>> ================================ RESTART ================================
>>> 
>>> myProgram()
I like pizza!

First of all, myProgram() still works as before. Secondly, this time the problem does not occur, i.e. the message “You have run the pizza module.” does not appear. This is exactly what we want. We don’t want this message to appear if we only import the pizza module.

But does the message appear when we run the pizza module? Let’s try! Running pizza.py yields the following in the Python-Shell:

>>> ================================ RESTART ================================
>>> 
You have run the pizza module.

We have been successful!

Summary:
If you encounter the statement below at the end of a module

if __name__ == "__main__":
    # Execute the code below only if this module is run,
    # but don't run it if this module is imported.
    # Some code here...

the following is achieved:
1. If you run the module, the code is executed.
2. If you import the module, the code is ignored.

Explanation:
If we run the module, Python sets the variable __name__ to “__main__” whereupon the if condition is fulfilled (see reference below).

References:
1) A Byte of Python
2) What does if __name__==“__main__”: do? (stackoverflow.com)
3) Python documentation

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: