This is an archived version of the course. Please see the latest version of the course.

What's in a __name__?

Remember that my_module.py is in itself a Python script. So we can actually type some code to do things like below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
FACTOR = 5

class Monster:
    def __init__(self, name="Me", food="cookies"):
        self.name = name
        self.food = food

    def talk(self):
        print(f"{self.name} love {self.food}!")


def spawn_monsters():
    return [Monster("Happy", "carrots"), 
            Monster("Bashful", "ice-creams"), 
            Monster("Wild", "cookies")]

def calculate_growthrate(adjustment=3):
    return 25 * FACTOR + adjustment

monster = Monster("Silly", "pizza")
monster.talk()

When you run the code with python3 my_module.py, it will print “Silly love pizza!”.

When you run python3 my_script.py (which import my_module), it will also print “Silly love pizza!”.

However, we do not want to see the code running when we import my_module – it is a library for people to use our functions/classes/variables after all.

We only want it to run when we execute my_module as a script (perhaps we just want to test that our class works). Can we do that? Of course!

What we do is to exploit the fact that Python will set a special variable __name__ as "__main__" only when you run your code as a script (e.g. using python3 my_module.py). So we just check that and only run our code when __name__ == "__main__"!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
FACTOR = 5

class Monster:
    def __init__(self, name="Me", food="cookies"):
        self.name = name
        self.food = food

    def talk(self):
        print(f"{self.name} love {self.food}!")

def spawn_monsters():
    return [Monster("Happy", "carrots"), 
            Monster("Bashful", "ice-creams"), 
            Monster("Wild", "cookies")]

def calculate_growthrate(adjustment=3):
    return 25 * FACTOR + adjustment

if __name__ == "__main__":
    monster = Monster("Silly", "pizza")
    monster.talk()

Now, if you run python3 my_module.py, you will see Silly love pizza!

But if you run python3 my_script.py which imports my_module, you will not see this.

While it is tempting to think of this as a main() method in Java, it is not quite the same since Python does not have or need a main function. So it is better not to think that way!