Python language basics 23: using the global __name__ attribute

Introduction

In the previous post we saw one way to break up the number guessing game into short functions. We saw examples of void methods and functions with and without parameters. We also said that there are usually several possible ways to organise the code into functions.

However, we also saw that calling the number guessing game from the command line didn’t execute anything. Python has no way of knowing what you want to do with the code, it only sees a collection of functions.

The solution is easy but we need to learn a new language construct first.

Double-underscore variables

Python has a small number of built-in variables surrounded by double underscores ‘__’. These are populated by Python during code execution, i.e. the Python runtime, and can be accessed in code if you need them.

One such variable is…

__name__

The question what the role of this variable is seems to be quite popular. This thread on Stack Overflow has got a lot of upvotes including the responses. I’ll copy the main points of the response with the highest number of votes here:

“When the Python interpreter reads a source file, it executes all of the code found in it. Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value “__main__”. If this file is being imported from another module, __name__ will be set to the module’s name.”

So when we executed…

python NumberGuessing.py

…on the command line, the “Python interpreter will execute the import statements and load those modules. It will then evaluate the def blocks.

Now, you might not understand all of that if you’re new to programming. The main thing to keep in mind right now is that numberGuessing.py is not an imported module. It is executed directly by the Python runtime. Hence this special __name__ variable will evaluate to “__main__” within that module. If you come from the world of Java, C, C++, C#, VB.NET then the word “main” will immediately sound familiar. The function called “main” defines the entry point of a programme in those languages.

We can use the __name__ variable to approximate this behaviour. We’ll check at the end of the number guess source file if __name__ is equal to “__main__” and then we’ll call the start_game() function. You can add the following

if __name__ == '__main__':
    start_game()

Many Python source files will have this statement so that the functions in those files can be tested individually. Also, the start_game function is the one which really starts the game as its name implies. We could simply call it “main” to adhere to the “main” function name convention in the popular languages above. You’ll see that quite often in real world Python files so that other programmers will recognise the main starting point of a source file.

Furthermore here comes another quote from the above SO thread to explain the purpose of this if-statement:

“One of the reasons for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.”

With this statement added to the end of the NumberGuessing.py file you’ll be able to start the game from the command line as well.

Read the next part here where we’ll discuss how to add arguments to the program from the command line.

Read all Python-related posts on this blog here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

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

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: