If name main python ошибка

So, here’s my situation.

I’m using PyDev in Eclipse, Python interpreter version 2.7.2 in Windows.

I’m using the built in multiprocessing library in an attempt to fork off a bunch of processes to parallelize a very compute-intensive loop. The tutorials I’ve looked at say to use,

if __name__ == "__main__":

to prevent it from spawning off near-infinite processes and bringing my system to its knees, essentially.

The problem is, I am calling this from a module, not my main script; as such, nothing after it EVER gets executed. No chance for parallelism at all. Of course, if I remove it, I get the infiniprocess spam that kills the machine executing the code.

For reference’s sake, here’s the relevant code:

from tribe import DataCache
from tribe import WorldThread
from tribe import Actor
from time import sleep
import multiprocessing

class World:
def __init__(self,numThreads,numActors,tickRate):
    print "Initalizing world..."
    self.cache = DataCache.DataCache()
    self.numThreads = numThreads
    self.numActors = numActors
    self.tickRate = tickRate
    self.actors = []
    self.processes = []
    for i in range(numActors):
        self.actors.append(Actor.Actor("test.xml",self.cache))
    print "Actors loaded."
def start_world(self):
    print "Starting world"
    run_world = True;
    while run_world:
        self.world_tick()
        sleep(2)

def world_tick(self):
        if __name__ == '__main__':
            print "World tick"
            actor_chunk = len(self.actors)/self.numThreads
            if len(self.processes)==0:
                for _ in range(self.numThreads):
                    new_process = multiprocessing.Process(WorldThread.WorldProcess.work, args=(_, self.actors[_*actor_chunk,(_+1)*actor_chunk]))

And the class it is calling:

class WorldProcess():
def __init__(self):
    print "World process initilized."
    ''' Really, I'm not sure what kind of setup we'll be doing here yet. '''
def work(self, process_number, actors):
    print "World process" + str(process_number) + " running."
    for actor in actors:
        actor.tick()
    print "World process" + str(process_number) + " completed."

Am I correct in my assessment that the whole if name == «main»: check only works if you have it in the executable script itself? If so, how do you safely fork off processes from within modules? If not, why isn’t it working here?

Short Answer

It’s boilerplate code that protects users from accidentally invoking the script when they didn’t intend to. Here are some common problems when the guard is omitted from a script:

  • If you import the guardless script in another script (e.g. import my_script_without_a_name_eq_main_guard), then the latter script will trigger the former to run at import time and using the second script’s command line arguments. This is almost always a mistake.

  • If you have a custom class in the guardless script and save it to a pickle file, then unpickling it in another script will trigger an import of the guardless script, with the same problems outlined in the previous bullet.

Long Answer

To better understand why and how this matters, we need to take a step back to understand how Python initializes scripts and how this interacts with its module import mechanism.

Whenever the Python interpreter reads a source file, it does two things:

  • it sets a few special variables like __name__, and then

  • it executes all of the code found in the file.

Let’s see how this works and how it relates to your question about the __name__ checks we always see in Python scripts.

Code Sample

Let’s use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called foo.py.

# Suppose this is foo.py.

print("before import")
import math

print("before function_a")
def function_a():
    print("Function A")

print("before function_b")
def function_b():
    print("Function B {}".format(math.sqrt(100)))

print("before __name__ guard")
if __name__ == '__main__':
    function_a()
    function_b()
print("after __name__ guard")

Special Variables

When the Python interpreter reads a source file, it first defines a few special variables. In this case, we care about the __name__ variable.

When Your Module Is the Main Program

If you are running your module (the source file) as the main program, e.g.

python foo.py

the interpreter will assign the hard-coded string "__main__" to the __name__ variable, i.e.

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 

When Your Module Is Imported By Another

On the other hand, suppose some other module is the main program and it imports your module. This means there’s a statement like this in the main program, or in some other module the main program imports:

# Suppose this is in some other main program.
import foo

The interpreter will search for your foo.py file (along with searching for a few other variants), and prior to executing that module, it will assign the name "foo" from the import statement to the __name__ variable, i.e.

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"

Executing the Module’s Code

After the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation.

Always

  1. It prints the string "before import" (without quotes).

  2. It loads the math module and assigns it to a variable called math. This is equivalent to replacing import math with the following (note that __import__ is a low-level function in Python that takes a string and triggers the actual import):

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
  1. It prints the string "before function_a".

  2. It executes the def block, creating a function object, then assigning that function object to a variable called function_a.

  3. It prints the string "before function_b".

  4. It executes the second def block, creating another function object, then assigning it to a variable called function_b.

  5. It prints the string "before __name__ guard".

Only When Your Module Is the Main Program

  1. If your module is the main program, then it will see that __name__ was indeed set to "__main__" and it calls the two functions, printing the strings "Function A" and "Function B 10.0".

Only When Your Module Is Imported by Another

  1. (instead) If your module is not the main program but was imported by another one, then __name__ will be "foo", not "__main__", and it’ll skip the body of the if statement.

Always

  1. It will print the string "after __name__ guard" in both situations.

Summary

In summary, here’s what’d be printed in the two cases:

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard

Why Does It Work This Way?

You might naturally wonder why anybody would want this. Well, sometimes you want to write a .py file that can be both used by other programs and/or modules as a module, and can also be run as the main program itself. Examples:

  • Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.

  • Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing .py files like your script and running special test functions. You don’t want it to try running the script just because it’s importing the module.

  • Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.

Beyond those examples, it’s elegant that running a script in Python is just setting up a few magic variables and importing the script. «Running» the script is a side effect of importing the script’s module.

Food for Thought

  • Question: Can I have multiple __name__ checking blocks? Answer: it’s strange to do so, but the language won’t stop you.

  • Suppose the following is in foo2.py. What happens if you say python foo2.py on the command-line? Why?

# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
  • Now, figure out what will happen in foo3.py (having removed the __name__ check):
# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo3 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
print("m1")
function_a()
print("m2")
print("t2")
  • What will this do when used as a script? When imported as a module?
# Suppose this is in foo4.py
__name__ = "__main__"

def bar():
    print("bar")
    
print("before __name__ guard")
if __name__ == "__main__":
    bar()
print("after __name__ guard")

Swifty's user avatar

Swifty

2,7502 gold badges3 silver badges21 bronze badges

answered Jan 7, 2009 at 4:26

Mr Fooz's user avatar

Mr FoozMr Fooz

109k6 gold badges73 silver badges101 bronze badges

21

When your script is run by passing it as a command to the Python interpreter,

python myscript.py

all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets run. Unlike other languages, there’s no main() function that gets run automatically — the main() function is implicitly all the code at the top level.

In this case, the top-level code is an if block. __name__ is a built-in variable which evaluates to the name of the current module. However, if a module is being run directly (as in myscript.py above), then __name__ instead is set to the string "__main__". Thus, you can test whether your script is being run directly or being imported by something else by testing

if __name__ == "__main__":
    ...

If your script is being imported into another module, its various function and class definitions will be imported and its top-level code will be executed, but the code in the then-body of the if clause above won’t get run as the condition is not met. As a basic example, consider the following two scripts:

# file one.py
def func():
    print("func() in one.py")

print("top-level in one.py")

if __name__ == "__main__":
    print("one.py is being run directly")
else:
    print("one.py is being imported into another module")
# file two.py
import one

print("top-level in two.py")
one.func()

if __name__ == "__main__":
    print("two.py is being run directly")
else:
    print("two.py is being imported into another module")

Now, if you invoke the interpreter as

python one.py

The output will be

top-level in one.py
one.py is being run directly

If you run two.py instead:

python two.py

You get

top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly

Thus, when module one gets loaded, its __name__ equals "one" instead of "__main__".

Tonechas's user avatar

Tonechas

13.4k16 gold badges46 silver badges80 bronze badges

answered Jan 7, 2009 at 4:28

Adam Rosenfield's user avatar

Adam RosenfieldAdam Rosenfield

391k98 gold badges513 silver badges589 bronze badges

2

Create the following two files:

# a.py

import b
# b.py

print("__name__ equals " + __name__)

if __name__ == '__main__':
    print("if-statement was executed")

Now run each file individually.


Running python a.py:

$ python a.py
__name__ equals b

When a.py is executed, it imports the module b. This causes all the code inside b to run. Python sets globals()['__name__'] in the b module to the module’s name, b.

Running python b.py:

$ python b.py
__name__ equals __main__
if-statement was executed

When only the file b.py is executed, Python sets globals()['__name__'] in this file to "__main__". Therefore, the if statement evaluates to True this time.

Mateen Ulhaq's user avatar

Mateen Ulhaq

24.7k19 gold badges102 silver badges135 bronze badges

answered Jan 7, 2009 at 11:35

pi.'s user avatar

pi.pi.

21.1k8 gold badges39 silver badges59 bronze badges

0

What does the if __name__ == "__main__": do?

To outline the basics:

  • The global variable, __name__, in the module that is the entry point to your program, is '__main__'. Otherwise, it’s the name you import the module by.

  • So, code under the if block will only run if the module is the entry point to your program.

  • It allows the code in the module to be importable by other modules, without executing the code block beneath on import.


Why do we need this?

Developing and Testing Your Code

Say you’re writing a Python script designed to be used as a module:

def do_important():
    """This function does something very important"""

You could test the module by adding this call of the function to the bottom:

do_important()

and running it (on a command prompt) with something like:

~$ python important.py

The Problem

However, if you want to import the module to another script:

import important

On import, the do_important function would be called, so you’d probably comment out your function call, do_important(), at the bottom.

# do_important() # I must remember to uncomment to execute this!

And then you’ll have to remember whether or not you’ve commented out your test function call. And this extra complexity would mean you’re likely to forget, making your development process more troublesome.

A Better Way

The __name__ variable points to the namespace wherever the Python interpreter happens to be at the moment.

Inside an imported module, it’s the name of that module.

But inside the primary module (or an interactive Python session, i.e. the interpreter’s Read, Eval, Print Loop, or REPL) you are running everything from its "__main__".

So if you check before executing:

if __name__ == "__main__":
    do_important()

With the above, your code will only execute when you’re running it as the primary module (or intentionally call it from another script).

An Even Better Way

There’s a Pythonic way to improve on this, though.

What if we want to run this business process from outside the module?

If we put the code we want to exercise as we develop and test in a function like this and then do our check for '__main__' immediately after:

def main():
    """business logic for when running this module as the primary one!"""
    setup()
    foo = do_important()
    bar = do_even_more_important(foo)
    for baz in bar:
        do_super_important(baz)
    teardown()

# Here's our payoff idiom!
if __name__ == '__main__':
    main()

We now have a final function for the end of our module that will run if we run the module as the primary module.

It will allow the module and its functions and classes to be imported into other scripts without running the main function, and will also allow the module (and its functions and classes) to be called when running from a different '__main__' module, i.e.

import important
important.main()

This idiom can also be found in the Python documentation in an explanation of the __main__ module. That text states:

This module represents the (otherwise anonymous) scope in which the
interpreter’s main program executes — commands read either from
standard input, from a script file, or from an interactive prompt. It
is this environment in which the idiomatic “conditional script” stanza
causes a script to run:

if __name__ == '__main__':
    main()

answered Nov 23, 2013 at 4:38

Russia Must Remove Putin's user avatar

2

if __name__ == "__main__" is the part that runs when the script is run from (say) the command line using a command like python myscript.py.

Mark Amery's user avatar

Mark Amery

144k81 gold badges406 silver badges459 bronze badges

answered Jan 7, 2009 at 4:14

Harley Holcombe's user avatar

Harley HolcombeHarley Holcombe

176k15 gold badges70 silver badges63 bronze badges

2

What does if __name__ == "__main__": do?

__name__ is a global variable (in Python, global actually means on the module level) that exists in all namespaces. It is typically the module’s name (as a str type).

As the only special case, however, in whatever Python process you run, as in mycode.py:

python mycode.py

the otherwise anonymous global namespace is assigned the value of '__main__' to its __name__.

Thus, including the final lines

if __name__ == '__main__':
    main()
  • at the end of your mycode.py script,
  • when it is the primary, entry-point module that is run by a Python process,

will cause your script’s uniquely defined main function to run.

Another benefit of using this construct: you can also import your code as a module in another script and then run the main function if and when your program decides:

import mycode
# ... any amount of other code
mycode.main()

Mateen Ulhaq's user avatar

Mateen Ulhaq

24.7k19 gold badges102 silver badges135 bronze badges

answered Oct 14, 2014 at 20:22

Russia Must Remove Putin's user avatar

0

There are lots of different takes here on the mechanics of the code in question, the «How», but for me none of it made sense until I understood the «Why». This should be especially helpful for new programmers.

Take file «ab.py»:

def a():
    print('A function in ab file');
a()

And a second file «xy.py»:

import ab
def main():
    print('main function: this is where the action is')
def x():
    print ('peripheral task: might be useful in other projects')
x()
if __name__ == "__main__":
    main()

What is this code actually doing?

When you execute xy.py, you import ab. The import statement runs the module immediately on import, so ab‘s operations get executed before the remainder of xy‘s. Once finished with ab, it continues with xy.

The interpreter keeps track of which scripts are running with __name__. When you run a script — no matter what you’ve named it — the interpreter calls it "__main__", making it the master or ‘home’ script that gets returned to after running an external script.

Any other script that’s called from this "__main__" script is assigned its filename as its __name__ (e.g., __name__ == "ab.py"). Hence, the line if __name__ == "__main__": is the interpreter’s test to determine if it’s interpreting/parsing the ‘home’ script that was initially executed, or if it’s temporarily peeking into another (external) script. This gives the programmer flexibility to have the script behave differently if it’s executed directly vs. called externally.

Let’s step through the above code to understand what’s happening, focusing first on the unindented lines and the order they appear in the scripts. Remember that function — or def — blocks don’t do anything by themselves until they’re called. What the interpreter might say if mumbled to itself:

  • Open xy.py as the ‘home’ file; call it "__main__" in the __name__ variable.
  • Import and open file with the __name__ == "ab.py".
  • Oh, a function. I’ll remember that.
  • Ok, function a(); I just learned that. Printing ‘A function in ab file‘.
  • End of file; back to "__main__"!
  • Oh, a function. I’ll remember that.
  • Another one.
  • Function x(); ok, printing ‘peripheral task: might be useful in other projects‘.
  • What’s this? An if statement. Well, the condition has been met (the variable __name__ has been set to "__main__"), so I’ll enter the main() function and print ‘main function: this is where the action is‘.

The bottom two lines mean: «If this is the "__main__" or ‘home’ script, execute the function called main()«. That’s why you’ll see a def main(): block up top, which contains the main flow of the script’s functionality.

Why implement this?

Remember what I said earlier about import statements? When you import a module it doesn’t just ‘recognize’ it and wait for further instructions — it actually runs all the executable operations contained within the script. So, putting the meat of your script into the main() function effectively quarantines it, putting it in isolation so that it won’t immediately run when imported by another script.

Again, there will be exceptions, but common practice is that main() doesn’t usually get called externally. So you may be wondering one more thing: if we’re not calling main(), why are we calling the script at all? It’s because many people structure their scripts with standalone functions that are built to be run independent of the rest of the code in the file. They’re then later called somewhere else in the body of the script. Which brings me to this:

But the code works without it

Yes, that’s right. These separate functions can be called from an in-line script that’s not contained inside a main() function. If you’re accustomed (as I am, in my early learning stages of programming) to building in-line scripts that do exactly what you need, and you’ll try to figure it out again if you ever need that operation again … well, you’re not used to this kind of internal structure to your code, because it’s more complicated to build and it’s not as intuitive to read.

But that’s a script that probably can’t have its functions called externally, because if it did it would immediately start calculating and assigning variables. And chances are if you’re trying to re-use a function, your new script is related closely enough to the old one that there will be conflicting variables.

In splitting out independent functions, you gain the ability to re-use your previous work by calling them into another script. For example, «example.py» might import «xy.py» and call x(), making use of the ‘x’ function from «xy.py». (Maybe it’s capitalizing the third word of a given text string; creating a NumPy array from a list of numbers and squaring them; or detrending a 3D surface. The possibilities are limitless.)

(As an aside, this question contains an answer by @kindall that finally helped me to understand — the why, not the how. Unfortunately it’s been marked as a duplicate of this one, which I think is a mistake.)

answered Sep 29, 2016 at 4:33

joechoj's user avatar

joechojjoechoj

1,33910 silver badges13 bronze badges

0

The code under if __name__ == '__main__': will only be executed if the module is invoked as a script.

As an example, consider the following module my_test_module.py:

# my_test_module.py

print('This is going to be printed out, no matter what')

if __name__ == '__main__':
    print('This is going to be printed out, only if user invokes the module as a script')

First possibility: Import my_test_module.py in another module

# main.py

import my_test_module

if __name__ == '__main__':
    print('Hello from main.py')

Now if you invoke main.py:

python main.py

>> 'This is going to be printed out, no matter what'
>> 'Hello from main.py'

Note that only the top-level print() statement in my_test_module is executed.


Second possibility: Invoke my_test_module.py as a script

Now if you run my_test_module.py as a Python script, both print() statements will be executed:

python my_test_module.py

>>> 'This is going to be printed out, no matter what'
>>> 'This is going to be printed out, only if user invokes the module as a script'

For a more comprehensive explanation, you can read What does if __name__ == '__main__' do in Python.

answered Feb 1, 2020 at 13:26

Giorgos Myrianthous's user avatar

0

When there are certain statements in our module (M.py) we want to be executed when it’ll be running as main (not imported), we can place those statements (test-cases, print statements) under this if block.

As by default (when module running as main, not imported) the __name__ variable is set to "__main__", and when it’ll be imported the __name__ variable will get a different value, most probably the name of the module ('M').
This is helpful in running different variants of a modules together, and separating their specific input & output statements and also if there are any test-cases.

In short, use this ‘if __name__ == "main" ‘ block to prevent (certain) code from being run when the module is imported.

Peter Mortensen's user avatar

answered Apr 3, 2013 at 14:09

Nabeel Ahmed's user avatar

Nabeel AhmedNabeel Ahmed

18.4k4 gold badges58 silver badges63 bronze badges

0

Put simply, __name__ is a variable defined for each script that defines whether the script is being run as the main module or it is being run as an imported module.

So if we have two scripts;

#script1.py
print "Script 1's name: {}".format(__name__)

and

#script2.py
import script1
print "Script 2's name: {}".format(__name__)

The output from executing script1 is

Script 1's name: __main__

And the output from executing script2 is:

Script1's name is script1
Script 2's name: __main__

As you can see, __name__ tells us which code is the ‘main’ module.
This is great, because you can just write code and not have to worry about structural issues like in C/C++, where, if a file does not implement a ‘main’ function then it cannot be compiled as an executable and if it does, it cannot then be used as a library.

Say you write a Python script that does something great and you implement a boatload of functions that are useful for other purposes. If I want to use them I can just import your script and use them without executing your program (given that your code only executes within the if __name__ == "__main__": context). Whereas in C/C++ you would have to portion out those pieces into a separate module that then includes the file. Picture the situation below;

Complicated importing in C

The arrows are import links. For three modules each trying to include the previous modules code there are six files (nine, counting the implementation files) and five links. This makes it difficult to include other code into a C project unless it is compiled specifically as a library. Now picture it for Python:

Elegant importing in Python

You write a module, and if someone wants to use your code they just import it and the __name__ variable can help to separate the executable portion of the program from the library part.

Peter Mortensen's user avatar

answered Oct 15, 2016 at 9:07

redbandit's user avatar

redbanditredbandit

2,13216 silver badges12 bronze badges

1

Let’s look at the answer in a more abstract way:

Suppose we have this code in x.py:

...
<Block A>
if __name__ == '__main__':
    <Block B>
...

Blocks A and B are run when we are running x.py.

But just block A (and not B) is run when we are running another module, y.py for example, in which x.py is imported and the code is run from there (like when a function in x.py is called from y.py).

kubuntu's user avatar

kubuntu

2,5251 gold badge22 silver badges24 bronze badges

answered Jan 20, 2015 at 17:48

Alisa's user avatar

AlisaAlisa

2,8923 gold badges31 silver badges44 bronze badges

0

To be short, you need to know several points:

  1. import a action actually runs all that can be run in a.py, meaning each line in a.py

  2. Because of point 1, you may not want everything to be run in a.py when importing it

  3. To solve the problem in point 2, Python allows you to use a condition check

  4. __name__ is an implicit variable in all .py modules:

  • when a.py is imported, the value of __name__ of a.py module is set to its file name «a«
  • when a.py is run directly using «python a.py«, the value of __name__ is set to a string __main__
  1. Based on the mechanism how Python sets the variable __name__ for each module, do you know how to achieve point 3? The answer is fairly easy, right? Use an if condition: if __name__ == "__main__": // do A
  • then python a.py will run the part // do A
  • and import a will skip the part // do A
  1. You can even put if __name__ == "a" depending on your functional need, but rarely do

The important thing that Python is special at is point 4! The rest is just basic logic.

I’ve been reading so much throughout the answers on this page. I would say, if you know the thing, for sure you will understand those answers, otherwise, you are still confused.

Peter Mortensen's user avatar

answered Jun 24, 2018 at 15:48

jack's user avatar

jackjack

1,78714 silver badges30 bronze badges

0

When you run Python interactively the local __name__ variable is assigned a value of __main__. Likewise, when you execute a Python module from the command line, rather than importing it into another module, its __name__ attribute is assigned a value of __main__, rather than the actual name of the module. In this way, modules can look at their own __name__ value to determine for themselves how they are being used, whether as support for another program or as the main application executed from the command line. Thus, the following idiom is quite common in Python modules:

if __name__ == '__main__':
    # Do something appropriate here, like calling a
    # main() function defined elsewhere in this module.
    main()
else:
    # Do nothing. This module has been imported by another
    # module that wants to make use of the functions,
    # classes and other useful bits it has defined.

answered Dec 11, 2013 at 11:23

Zain's user avatar

ZainZain

1,2261 gold badge16 silver badges26 bronze badges

Consider:

if __name__ == "__main__":
    main()

It checks if the __name__ attribute of the Python script is "__main__". In other words, if the program itself is executed, the attribute will be __main__, so the program will be executed (in this case the main() function).

However, if your Python script is used by a module, any code outside of the if statement will be executed, so if __name__ == "__main__" is used just to check if the program is used as a module or not, and therefore decides whether to run the code.

tripleee's user avatar

tripleee

176k34 gold badges275 silver badges318 bronze badges

answered Aug 22, 2017 at 18:53

Larry's user avatar

LarryLarry

1,3122 gold badges15 silver badges22 bronze badges

0

Before explaining anything about if __name__ == '__main__' it is important to understand what __name__ is and what it does.

What is __name__?

__name__ is a DunderAlias — can be thought of as a global variable (accessible from modules) and works in a similar way to global.

It is a string (global as mentioned above) as indicated by type(__name__) (yielding <class 'str'>), and is an inbuilt standard for both Python 3 and Python 2 versions.

Where

It can not only be used in scripts but can also be found in both the interpreter and modules/packages.

Interpreter:

>>> print(__name__)
__main__
>>>

Script:

test_file.py:

print(__name__)

Resulting in __main__

Module or package:

somefile.py:

def somefunction():
    print(__name__)

test_file.py:

import somefile
somefile.somefunction()

Resulting in somefile

Notice that when used in a package or module, __name__ takes the name of the file. The path of the actual module or package path is not given, but has its own DunderAlias __file__, that allows for this.

You should see that, where __name__, where it is the main file (or program) will always return __main__, and if it is a module/package, or anything that is running off some other Python script, will return the name of the file where it has originated from.

Practice

Being a variable means that it’s value can be overwritten («can» does not mean «should»), overwriting the value of __name__ will result in a lack of readability. So do not do it, for any reason. If you need a variable define a new variable.

It is always assumed that the value of __name__ to be __main__ or the name of the file. Once again changing this default value will cause more confusion that it will do good, causing problems further down the line.

Example:

>>> __name__ = 'Horrify' # Change default from __main__
>>> if __name__ == 'Horrify': print(__name__)
...
>>> else: print('Not Horrify')
...
Horrify
>>>

It is considered good practice in general to include the if __name__ == '__main__' in scripts.

Now to answer if __name__ == '__main__':

Now we know the behaviour of __name__ things become clearer:

An if is a flow control statement that contains the block of code will execute if the value given is true. We have seen that __name__ can take either
__main__ or the file name it has been imported from.

This means that if __name__ is equal to __main__ then the file must be the main file and must actually be running (or it is the interpreter), not a module or package imported into the script.

If indeed __name__ does take the value of __main__ then whatever is in that block of code will execute.

This tells us that if the file running is the main file (or you are running from the interpreter directly) then that condition must execute. If it is a package then it should not, and the value will not be __main__.

Modules

__name__ can also be used in modules to define the name of a module

Variants

It is also possible to do other, less common but useful things with __name__, some I will show here:

Executing only if the file is a module or package

if __name__ != '__main__':
    # Do some useful things 

Running one condition if the file is the main one and another if it is not

if __name__ == '__main__':
    # Execute something
else:
    # Do some useful things

You can also use it to provide runnable help functions/utilities on packages and modules without the elaborate use of libraries.

It also allows modules to be run from the command line as main scripts, which can be also very useful.

tripleee's user avatar

tripleee

176k34 gold badges275 silver badges318 bronze badges

answered Apr 3, 2018 at 19:32

Xantium's user avatar

XantiumXantium

11.2k10 gold badges62 silver badges89 bronze badges

0

I think it’s best to break the answer in depth and in simple words:

__name__: Every module in Python has a special attribute called __name__.
It is a built-in variable that returns the name of the module.

__main__: Like other programming languages, Python too has an execution entry point, i.e., main. '__main__' is the name of the scope in which top-level code executes. Basically you have two ways of using a Python module: Run it directly as a script, or import it. When a module is run as a script, its __name__ is set to __main__.

Thus, the value of the __name__ attribute is set to __main__ when the module is run as the main program. Otherwise the value of __name__ is set to contain the name of the module.

Peter Mortensen's user avatar

answered Nov 30, 2016 at 6:47

Taufiq Rahman's user avatar

Taufiq RahmanTaufiq Rahman

5,6102 gold badges36 silver badges44 bronze badges

It is a special for when a Python file is called from the command line. This is typically used to call a «main()» function or execute other appropriate startup code, like commandline arguments handling for instance.

It could be written in several ways. Another is:

def some_function_for_instance_main():
    dosomething()


__name__ == '__main__' and some_function_for_instance_main()

I am not saying you should use this in production code, but it serves to illustrate that there is nothing «magical» about if __name__ == '__main__'.

It just a convention for invoking a main function in Python files.

answered Jan 24, 2013 at 13:48

Prof. Falken's user avatar

Prof. FalkenProf. Falken

24.3k19 gold badges100 silver badges173 bronze badges

6

There are a number of variables that the system (Python interpreter) provides for source files (modules). You can get their values anytime you want, so, let us focus on the __name__ variable/attribute:

When Python loads a source code file, it executes all of the code found in it. (Note that it doesn’t call all of the methods and functions defined in the file, but it does define them.)

Before the interpreter executes the source code file though, it defines a few special variables for that file; __name__ is one of those special variables that Python automatically defines for each source code file.

If Python is loading this source code file as the main program (i.e. the file you run), then it sets the special __name__ variable for this file to have a value «__main__».

If this is being imported from another module, __name__ will be set to that module’s name.

So, in your example in part:

if __name__ == "__main__":
   lock = thread.allocate_lock()
   thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
   thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))

means that the code block:

lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))

will be executed only when you run the module directly; the code block will not execute if another module is calling/importing it because the value of __name__ will not equal to «main» in that particular instance.

Hope this helps out.

answered Nov 25, 2015 at 12:26

codewizard's user avatar

codewizardcodewizard

3863 silver badges8 bronze badges

1

if __name__ == "__main__": is basically the top-level script environment, and it specifies the interpreter that (‘I have the highest priority to be executed first’).

'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.

if __name__ == "__main__":
    # Execute only if run as a script
    main()

Peter Mortensen's user avatar

answered Apr 24, 2016 at 8:23

The Gr8 Adakron's user avatar

The Gr8 AdakronThe Gr8 Adakron

1,1991 gold badge12 silver badges15 bronze badges

Consider:

print __name__

The output for the above is __main__.

if __name__ == "__main__":
  print "direct method"

The above statement is true and prints «direct method». Suppose if they imported this class in another class it doesn’t print «direct method» because, while importing, it will set __name__ equal to "first model name".

simhumileco's user avatar

simhumileco

32k16 gold badges137 silver badges115 bronze badges

answered Jun 22, 2016 at 10:47

Janarthanan Ramu's user avatar

In simple words:

The code you see under if __name__ == "__main__": will only get called upon when your Python file is executed as python example1.py

However, if you wish to import your Python file example1.py as a module to work with another Python file, say example2.py, the code under if __name__ == "__main__": will not run or take any effect.

tripleee's user avatar

tripleee

176k34 gold badges275 silver badges318 bronze badges

answered Oct 22, 2020 at 18:01

Babatunde Mustapha's user avatar

You can make the file usable as a script as well as an importable module.

fibo.py (a module named fibo)

# Other modules can IMPORT this MODULE to use the function fib
def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a+b
    print()

# This allows the file to be used as a SCRIPT
if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

Reference: https://docs.python.org/3.5/tutorial/modules.html

answered Mar 13, 2017 at 21:44

kgf3JfUtW's user avatar

kgf3JfUtWkgf3JfUtW

13.8k11 gold badges58 silver badges81 bronze badges

The reason for

if __name__ == "__main__":
    main()

is primarily to avoid the import lock problems that would arise from having code directly imported. You want main() to run if your file was directly invoked (that’s the __name__ == "__main__" case), but if your code was imported then the importer has to enter your code from the true main module to avoid import lock problems.

A side-effect is that you automatically sign on to a methodology that supports multiple entry points. You can run your program using main() as the entry point, but you don’t have to. While setup.py expects main(), other tools use alternate entry points. For example, to run your file as a gunicorn process, you define an app() function instead of a main(). Just as with setup.py, gunicorn imports your code so you don’t want it do do anything while it’s being imported (because of the import lock issue).

answered Sep 22, 2017 at 18:32

personal_cloud's user avatar

personal_cloudpersonal_cloud

3,9693 gold badges28 silver badges38 bronze badges

0

If you are a beginner, probably the only answer you need right now is that this code is unnecessary for a simple script. It is only useful if you want to be able to import your script (or unpickle etc; see the other answers here for some other non-beginner scenarios).

In slightly different words, the if __name__ guard is a mechanism for hiding code from other code. If you don’t have a specific reason to hide something, don’t: If you don’t need to hide some code from import, don’t put it behind this guard, and if you do, hide as little as possible.

In slightly more detail, let’s say you have a simple script fib.py (adapted from this answer):

# XXX FIXME: useless (see below)
if __name__ == "__main__":
    n = int(input('Write a number: '))
    a, b = 0, 1
    while b < n:
        a, b = b, a+b
    print('Fibonacci number %i: %i' % (n, b))

Now, if you simply run python fib.py it works fine. But __name__ will always be "__main__" in this scenario, so the condition is actually unnecessary. The script could be simplified to just

n = int(input('Write a number: '))
a, b = 0, 1
while b < n:
    a, b = b, a+b
print('Fibonacci number %i: %i' % (n, b))

Now, you can’t import fib with the new version, but if you didn’t plan to do that in the first place, this version is actually better, because it’s simpler and clearer.

If you do want to be able to import fib, the first version is useless, too, because the useful code is in a section which will not run when you import this file (in which case __name__ will not be "__main__"). The proper design in that case would be to refactor the code so that the useful parts are in a function you can run when you want to after you have imported it.

def main():
    n = int(input('Write a number: '))
    a, b = 0, 1
    while b < n:
        a, b = b, a+b
    print('Fibonacci number %i: %i' % (n, b))

if __name__ == "__main__":
    main()

Now, if you import fib, the call to main() will not be executed; but when you run python fib.py, it will.

Actually, a better design still would be to isolate the reusable part (the actual calculation) from the user-visible input/output:

def fibn(n: int) -> int:
    a, b = 0, 1
    while b < n:
        a, b = b, a+b
    return b

def main() -> None:
    n = int(input('Write a number: '))
    print('Fibonacci number %i: %i' % (n, fibn(n)))

if __name__ == "__main__":
    main()

Now, you can from fib import fibn and call the fibn() function from the code which performs this import.

(I called the function fibn() just to make it clearer what is what in this example. In real life, you might call it fib() and do from fib import fib.)

Similarly, you could import and call the main function if you wanted to reuse it.

Returning to the code in the question, I would similarly move the code from the if into a function as well, so that callers can invoke that function if they want to.

def main():
    lock = thread.allocate_lock()
    thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
    thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))

if __name__ == "__main__":
    main()

This changes the scope of the lock variable; if the surrounding code needs access to it, you will need to make it global (or, perhaps, better, refactor main to return lock, and have the caller capture the value in a local variable of its own).

(Unlike in languages like C, the name main has no specific meaning to Python; but it’s a common convention to use it as the name of the thing which will be run. You still have to actually explicitly call it, like main(), unlike in C.)

answered Oct 30, 2021 at 9:46

tripleee's user avatar

tripleeetripleee

176k34 gold badges275 silver badges318 bronze badges

3

Every module in Python has an attribute called __name__. The value of __name__ attribute is __main__ when the module is run directly, like python my_module.py. Otherwise (like when you say import my_module) the value of __name__ is the name of the module.

Small example to explain in short.

Script test.py

apple = 42

def hello_world():
    print("I am inside hello_world")

if __name__ == "__main__":
    print("Value of __name__ is: ", __name__)
    print("Going to call hello_world")
    hello_world()

We can execute this directly as

python test.py

Output

Value of __name__ is: __main__
Going to call hello_world
I am inside hello_world

Now suppose we call the above script from another script:

Script external_calling.py

import test

print(test.apple)
test.hello_world()

print(test.__name__)

When you execute this,

python external_calling.py

Output

42
I am inside hello_world
test

So, the above is self-explanatory that when you call test from another script, if loop __name__ in test.py will not execute.

Peter Mortensen's user avatar

answered Jun 12, 2019 at 9:28

LOrD_ARaGOrN's user avatar

LOrD_ARaGOrNLOrD_ARaGOrN

3,9043 gold badges27 silver badges49 bronze badges

This answer is for Java programmers learning Python.
Every Java file typically contains one public class. You can use that class in two ways:

  1. Call the class from other files. You just have to import it in the calling program.

  2. Run the class stand alone, for testing purposes.

For the latter case, the class should contain a public static void main() method. In Python this purpose is served by the globally defined label '__main__'.

eyllanesc's user avatar

eyllanesc

236k19 gold badges170 silver badges242 bronze badges

answered Oct 7, 2018 at 4:52

Raja's user avatar

RajaRaja

1,00614 silver badges15 bronze badges

0

If this .py file are imported by other .py files, the code under the if statement will not be executed.

If this .py are run by python this_py.py under shell, or double clicked in Windows. the code under the if statement will be executed.

It is usually written for testing.

tripleee's user avatar

tripleee

176k34 gold badges275 silver badges318 bronze badges

answered Jun 19, 2018 at 11:44

pah8J's user avatar

pah8Jpah8J

8079 silver badges15 bronze badges

We see if __name__ == '__main__': quite often.

It checks if a module is being imported or not.

In other words, the code within the if block will be executed only when the code runs directly. Here directly means not imported.

Let’s see what it does using a simple code that prints the name of the module:

# test.py
def test():
   print('test module name=%s' %(__name__))

if __name__ == '__main__':
   print('call test()')
   test()

If we run the code directly via python test.py, the module name is __main__:

call test()
test module name=__main__

tripleee's user avatar

tripleee

176k34 gold badges275 silver badges318 bronze badges

answered Apr 4, 2018 at 14:32

Ali Hallaji's user avatar

Ali HallajiAli Hallaji

3,7522 gold badges29 silver badges36 bronze badges

If the Python interpreter is running a particular module then the __name__ global variable will have the value "__main__":

def a():
    print("a")

def b():
    print("b")

if __name__ == "__main__":

        print ("you can see me")
        a()
else:

        print ("You can't see me")
        b()

When you run this script, it prints:

you can see me
a

If you import this file, say A to file B, and execute the file B then if __name__ == "__main__" in file A becomes False, so it prints:

You can't see me
b

Javad's user avatar

Javad

2,0313 gold badges13 silver badges23 bronze badges

answered Jul 30, 2019 at 16:22

Nikil Munireddy's user avatar

All the answers have pretty much explained the functionality. But I will provide one example of its usage which might help clearing out the concept further.

Assume that you have two Python files, a.py and b.py. Now, a.py imports b.py. We run the a.py file, where the import b.py code is executed first. Before the rest of the a.py code runs, the code in the file b.py must run completely.

In the b.py code, there is some code that is exclusive to that file b.py and we don’t want any other file (other than the b.py file), that has imported the b.py file, to run it.

So that is what this line of code checks. If it is the main file (i.e., b.py) running the code, which in this case it is not (a.py is the main file running), then only the code gets executed.

Javad's user avatar

Javad

2,0313 gold badges13 silver badges23 bronze badges

answered May 4, 2018 at 8:25

preetika mondal's user avatar

If you are having trouble finding the cause and solution of the error NameError: name ‘main’ is not defined in Python, this article may help you. In this article, I will identify the cause of the error and perform a fix by putting name main in quotes or on the Python version you are using. Post details below.

What causes the NameError: name ‘__main__’ is not defined error?

The statements contained in a source code file are all executed by the Python interpreter as it reads the file. Python gives the variable (__name__) the value (“__main__”) when it executes the “file containing the source code” as the main program.

When the main function is called, the “if” statement is read, and a check is made to see if the __name__ variable contains the value “__main__”. Python’s “__if name __” == “__main__” function enables you to launch source code files as standalone applications or reusable modules.

The main function has two applications in the Python interpreter:

  • __name__ is the module’s file name when it is used to load. If the condition in the if statement is not met, the __main__ source code will not be run.
  • __name__ = __ main__ when used to run something directly. The source code in __main__ will be run if the condition in the if statement is met. 

To validate the module name, the source code uses the “if” statement when it is run.

The error NameError: name ‘__main__’ is not defined happens you don’t put name __main__ in quotes.  

Example:

def main():
  print('This is a Python tutorial for beginnners.')
  
print('Hello')

if __name__ == __main__:
    main()

Output:

Traceback (most recent call last):
 File "./prog.py", line 6, in <module>
NameError: name '__main__' is not defined

How to solve this error?

Put name __main__ in quotes.

Example:

  • To fix the error NameError: name __main__ is not defined, enclose the special name __main__ in quotes.
def main():
  print('This is a Python tutorial for beginnners.')
  
print('Hello')

# Enclose the special name __main__ in quotes.
if __name__ == '__main__':
    main()

Output:

Hello
This is a Python tutorial for beginnners.

On Python 2 and Python 3 versions.

In Python 3, you can remove if__name__, and the program will still function properly.

Example:

def main():
  print('This is a Python tutorial for beginnners.')
  
print('Hello')

# Remove if__name__, and the program will still function properly.
main()

Output:

Hello
This is a Python tutorial for beginnners.

If you are still using Python 2.

Example:

def main():
  print('This is a Python tutorial for beginnners.')
  
print 'Hello'

# Enclose the special name __main__ in quotes.
if __name__ == '__main__':
    main()

Output:

Hello
This is a Python tutorial for beginnners.

Summary

I have shown the causes and given the remedies that fixed the error NameError: name ‘__main__’ is not defined in Python. This is a simple bug in Python. Remember to import it before using it. Please fix it as soon as possible. Good luck!

Jason Wilson

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.


Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

You can fix a RuntimeError when starting child processes by adding if name == ‘main’ to checking for the top-level environment in your code.

In this tutorial you will discover the RuntimeError common on Windows and MacOS when creating child processes and how to fix it.

Let’s get started.

RuntimeError When Starting a Child Process

It is common to get a RuntimeError when starting a new Process in Python.

The content of the error often looks as follows:

    An attempt has been made to start a new process before the

    current process has finished its bootstrapping phase.

    This probably means that you are not using fork to start your

    child processes and you have forgotten to use the proper idiom

    in the main module:

        if __name__ == ‘__main__’:

            freeze_support()

            …

    The «freeze_support()» line can be omitted if the program

    is not going to be frozen to produce an executable.

This will happen on Windows and MacOS where the default start method is ‘spawn‘. It may also happen when you configure your program to use the ‘spawn‘ start method on other platforms.

We can demonstrate this error with a worked example.

In this example we will configure a new child process to execute our custom task() function. We will then start the child process by calling the start() function.

The complete example is listed below.

# SuperFastPython.com

# example of missing __name__ == ‘__main__’

from multiprocessing import Process

# function executed in a new process

def task():

    print(‘Hello from a child process’, flush=True)

# create and configure a new process

process = Process(target=task)

# start the new process

process.start()

# wait for the new process to finish

process.join()

Running the example raises a RuntimeError on Windows and MacOS.

The RuntimeError is raised when we try to start the child process.

Specifically on the line:

A sample of the message reported by the RuntimeError is listed below.

Traceback (most recent call last):

  …

RuntimeError:

        An attempt has been made to start a new process before the

        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your

        child processes and you have forgotten to use the proper idiom

        in the main module:

            if __name__ == ‘__main__’:

                freeze_support()

                …

        The «freeze_support()» line can be omitted if the program

        is not going to be frozen to produce an executable.

This is a common error and is easy to fix.

Fix RuntimeError When Starting New Process

The fix involves checking if the code is running in the top-level environment and only then, attempt to start a new process.

This is a best practice.

The idiom for this fix, as stated in the message of the RuntimeError, is to use an if-statement and check if the name of the module is equal to the string ‘__main__‘.

For example:

...

# check for top-level environment

if __name__ == ‘__main__’:

# …

This is called “protecting the entry point” of the program.

Recall, that __name__ is a variable that refers to the name of the module executing the current code.

When a Python module or package is imported, __name__ is set to the module’s name. Usually, this is the name of the Python file itself without the .py extension:

— __main__ — Top-level code environment

Also, recall that ‘__main__‘ is the name of the top-level environment used to execute a Python program.

__main__ is the name of the environment where top-level code is run. “Top-level code” is the first user-specified Python module that starts running. It’s “top-level” because it imports all other modules that the program needs.

— __main__ — Top-level code environment

Using an if-statement to check if the module is the top-level environment and only starting child processes within that block will resolve the RuntimeError.

It means that if the Python file is imported, then the code protected by the if-statement will not run. It will only run when the Python file is run directly, e.g. is the top-level environment.

Some modules contain code that is intended for script use only, like parsing command-line arguments or fetching data from standard input. If a module like this was imported from a different module, for example to unit test it, the script code would unintentionally execute as well. This is where using the if __name__ == ‘__main__’ code block comes in handy. Code within this block won’t run unless the module is executed in the top-level environment.

— __main__ — Top-level code environment

The if-statement idiom is required, even if the entry point of the program calls a function that itself starts a child process.

This is only used for child processes created by the main process. Child processes themselves can create child processes without this check.

Confused by the multiprocessing module API?
Download my FREE PDF cheat sheet

Why Do We Need to Protect Entry Point?

We must protect the entry point when starting new processes from the main process using the ‘spawn‘ method.

The reason is because our Python script will be loaded and imported automatically for us by child processes.

This is required to execute our custom code and functions in new child processes.

If the entry point was not protected with an if-statement idiom checking for the top-level environment, then the script would execute again directly, rather than run a new child process as expected.

Protecting the entry point ensures that the program is only started once, that the tasks of the main process are only executed by the main process and not the child processes.


Free Python Multiprocessing Course

Download my multiprocessing API cheat sheet and as a bonus you will get FREE access to my 7-day email course.

Discover how to use the Python multiprocessing module including how to create and start child processes and how to use a mutex locks and semaphores.

Learn more
 


Example of Fix By Protecting Entry Point

We can demonstrate how to check for the top-level environment when starting a new process.

This can be achieved by updating the example above that resulted in a RuntimeError and adding a check if __name__ is equal to ‘__main__’.

For example:

# check for top-level environment

if __name__ == ‘__main__’:

    # create and configure a new process

    process = Process(target=task)

    # start the new process

    process.start()

    # wait for the new process to finish

    process.join()

Tying this together, the complete example is listed below.

# SuperFastPython.com

# example of starting a child process only in __main__

from multiprocessing import Process

# function executed in a new process

def task():

    print(‘Hello from a child process’, flush=True)

# check for top-level environment

if __name__ == ‘__main__’:

    # create and configure a new process

    process = Process(target=task)

    # start the new process

    process.start()

    # wait for the new process to finish

    process.join()

Running the example successfully starts a new child process.

The message is reported from the child process as expected.

Hello from a child process

Example of Fix by Changing Start Method

We can also fix the issue by changing the start method from ‘spawn‘ to ‘fork‘.

This fix only works on those platforms where the ‘fork’ method is supported, e.g. Unix and MacOS.

This can be achieved via the multiprocessing.set_start_method() function.

For example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

# SuperFastPython.com

# example of missing __name__ == ‘__main__’

from multiprocessing import set_start_method

from multiprocessing import Process

# function executed in a new process

def task():

    print(‘Hello from a child process’, flush=True)

# set the start method

set_start_method(‘fork’)

# create and configure a new process

process = Process(target=task)

# start the new process

process.start()

# wait for the new process to finish

process.join()

Running the example successfully starts a new child process.

The message is reported from the child process as expected.

Hello from a child process

Further Reading

This section provides additional resources that you may find helpful.

Books

  • Python Multiprocessing Jump-Start, Jason Brownlee, 2022 (my book!).
  • Multiprocessing API Interview Questions
  • Multiprocessing Module API Cheat Sheet

I would also recommend specific chapters in the books:

  • Effective Python, Brett Slatkin, 2019.
    • See: Chapter 7: Concurrency and Parallelism
  • High Performance Python, Ian Ozsvald and Micha Gorelick, 2020.
    • See: Chapter 9: The multiprocessing Module
  • Python in a Nutshell, Alex Martelli, et al., 2017.
    • See: Chapter: 14: Threads and Processes

Guides

  • Python Multiprocessing: The Complete Guide

APIs

  • multiprocessing — Process-based parallelism
  • PEP 371 — Addition of the multiprocessing package

    Takeaways

    You now know how to fix the RuntimeError caused by starting child processes with the ‘spawn‘ start method.

    Do you have any questions?
    Ask your questions in the comments below and I will do my best to answer.

    Photo by Ivan Ragozin on Unsplash

    Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: What Does if __name__ == «__main__» Mean in Python?

    You’ve likely encountered Python’s if __name__ == "__main__" idiom when reading other people’s code. No wonder—it’s widespread! You might have even used if __name__ == "__main__" in your own scripts. But did you use it correctly?

    Maybe you’ve programmed in a C-family language like Java before, and you wonder whether this construct is a clumsy accessory to using a main() function as an entry point.

    Syntactically, Python’s if __name__ == "__main__" idiom is just a normal conditional block:

     1if __name__ == "__main__":
     2    ...
    

    The indented block starting in line 2 contains all the code that Python will execute when the conditional statement in line 1 evaluates to True. In the code example above, the specific code logic that you’d put in the conditional block is represented with a placeholder ellipsis (...).

    So—if there’s nothing special about the if __name__ == "__main__" idiom, then why does it look confusing, and why does it continue to spark discussion in the Python community?

    If the idiom still seems a little cryptic, and you’re not completely sure what it does, why you might want it, and when to use it, then you’ve come to the right place! In this tutorial, you’ll learn all about Python’s if __name__ == "__main__" idiom—starting with what it really does in Python, and ending with a suggestion for a quicker way to refer to it.

    In Short: It Allows You to Execute Code When the File Runs as a Script, but Not When It’s Imported as a Module

    For most practical purposes, you can think of the conditional block that you open with if __name__ == "__main__" as a way to store code that should only run when your file is executed as a script.

    You’ll see what that means in a moment. For now, say you have the following file:

     1# echo.py
     2
     3def echo(text: str, repetitions: int = 3) -> str:
     4    """Imitate a real-world echo."""
     5    echoed_text = ""
     6    for i in range(repetitions, 0, -1):
     7        echoed_text += f"{text[-i:]}\n"
     8    return f"{echoed_text.lower()}."
     9
    10if __name__ == "__main__":
    11    text = input("Yell something at a mountain: ")
    12    print(echo(text))
    

    In this example, you define a function, echo(), that mimics a real-world echo by gradually printing fewer and fewer of the final letters of the input text.

    Below that, in lines 10 to 12, you use the if __name__ == "__main__" idiom. This code starts with the conditional statement if __name__ == "__main__" in line 10. In the indented lines, 11 and 12, you then collect user input and call echo() with that input. These two lines will execute when you run echo.py as a script from your command line:

    $ python echo.py
    Yell something at a mountain: HELLOOOO ECHOOOOOOOOOO
    ooo
    oo
    o
    .
    

    When you run the file as a script by passing the file object to your Python interpreter, the expression __name__ == "__main__" returns True. The code block under if then runs, so Python collects user input and calls echo().

    Try it out yourself! You can download all the code files that you’ll use in this tutorial from the link below:

    At the same time, if you import echo() in another module or a console session, then the nested code won’t run:

    >>>

    >>> from echo import echo
    >>> print(echo("Please help me I'm stuck on a mountain"))
    ain
    in
    n
    .
    

    In this case, you want to use echo() in the context of another script or interpreter session, so you won’t need to collect user input. Running input() would mess with your code by producing a side effect when importing echo.

    When you nest the code that’s specific to the script usage of your file under the if __name__ == "__main__" idiom, then you avoid running code that’s irrelevant for imported modules.

    Nesting code under if __name__ == "__main__" allows you to cater to different use cases:

    • Script: When run as a script, your code prompts the user for input, calls echo(), and prints the result.
    • Module: When you import echo as a module, then echo() gets defined, but no code executes. You provide echo() to the main code session without any side effects.

    By implementing the if __name__ == "__main__" idiom in your code, you set up an additional entry point that allows you to use echo() right from the command line.

    There you go! You’ve now covered the most important information about this topic. Still, there’s more to find out, and there are some subtleties that can help you build a deeper understanding of this code specifically and Python more generally.

    Read on to learn more about the name-main idiom, as this tutorial will refer to it for short.

    How Does the Name-Main Idiom Work?

    At its core, the idiom is a conditional statement that checks whether the value of the variable __name__ is equal to the string "__main__":

    • If the __name__ == "__main__" expression is True, then the indented code following the conditional statement executes.
    • If the __name__ == "__main__" expression is False, then Python skips the indented code.

    But when is __name__ equal to the string "__main__"? In the previous section, you learned that this is the case when you run your Python file as a script from the command line. While that covers most real-life use cases, maybe you want to go deeper.

    Python sets the global __name__ of a module equal to "__main__" if the Python interpreter runs your code in the top-level code environment:

    “Top-level code” is the first user-specified Python module that starts running. It’s “top-level” because it imports all other modules that the program needs. (Source)

    To better understand what that means, you’ll set up a small practical example. Create a Python file, call it namemain.py, and add one line of code:

    # namemain.py
    
    print(__name__, type(__name__))
    

    Your new file contains only a single line of code that prints the value and type of the global __name__ to the console.

    Spin up your terminal and run the Python file as a script:

    $ python namemain.py
    __main__ <class 'str'>
    

    The output shows you that the value of __name__ is the Python string "__main__" if you run your file as a script.

    Now you know the value of __name__ when your code is executed in the top-level code environment.

    But a conditional statement can only produce different results when the condition has a chance to evaluate in different ways. So, when is your code not run in the top-level code environment, and what happens to the value of __name__ in that case?

    The code in your file isn’t run in the top-level code environment if you import your module. In that case, Python sets __name__ to the module’s name.

    To try this out, start a Python console and import the code from namemain.py as a module:

    >>>

    >>> import namemain
    namemain <class 'str'>
    

    Python executes the code stored in the global namespace of namemain.py during the import, which means it’ll call print(__name__, type(__name__)) and write the output to the console.

    In this case, however, the value of the module’s __name__ is different. It points to "namemain", a string that’s equal to the module’s name.

    You just learned that for your top-level code environment, __name__ is always "__main__", so go ahead and confirm that within your interpreter session. Also check where the string "namemain" comes from:

    >>>

    >>> __name__
    '__main__'
    
    >>> namemain.__name__
    'namemain'
    

    The global __name__ has the value "__main__", and .__name__ for the imported namemain module has the value "namemain", which is the module’s name as a string.

    Now you know that the value of __name__ will have one of two values depending on where it lives:

    • In the top-level code environment, the value of __name__ is "__main__".
    • In an imported module, the value of __name__ is the module’s name as a string.

    Because Python follows these rules, you can find out whether or not a module is running in the top-level code environment. You do this by checking the value of __name__ with a conditional statement, which brings you full circle to the name-main idiom:

    # namemain.py
    
    print(__name__, type(__name__))
    
    if __name__ == "__main__":
        print("Nested code only runs in the top-level code environment")
    

    With this conditional check in place, you can declare code that only executes when the module is run in the top-level code environment.

    Add the idiom to namemain.py as shown in the code block above, then run the file as a script once more:

    $ python namemain.py
    __main__ <class 'str'>
    Nested code only runs in the top-level code environment
    

    When running your code as a script, both calls to print() execute.

    Next, start a new interpreter session and import namemain as a module once more:

    >>>

    >>> import namemain
    namemain <class 'str'>
    

    When you import your file as a module, the code that you nested under if __name__ == "__main__" doesn’t execute.

    Now that you know how the name-main idiom works in Python, you may wonder when and how exactly you should use it in your code—and when to avoid it!

    When Should You Use the Name-Main Idiom in Python?

    You use this idiom when you want to create an additional entry point for your script, so that your file is accessible as a stand-alone script as well as an importable module. You might want that when your script needs to collect user input.

    In the first section of this tutorial, you used the name-main idiom together with input() to collect user input when running echo.py as a script. That’s a great reason to use the name-main idiom!

    There are also other ways to collect user input directly from the command line. For example, you could create a command-line entry point for a small Python script with sys.argv and the name-main idiom:

     1# echo.py
     2
     3import sys
     4
     5def echo(text: str, repetitions: int = 3) -> str:
     6    """Imitate a real-world echo."""
     7    echoed_text = ""
     8    for i in range(repetitions, 0, -1):
     9        echoed_text += f"{text[-i:]}\n"
    10    return f"{echoed_text.lower()}."
    11
    12if __name__ == "__main__":
    13    text = " ".join(sys.argv[1:])
    14    print(echo(text))
    

    Instead of collecting user input with input(), you changed the code in echo.py so that your users can provide the text as arguments directly from the command line:

    $ python echo.py HELLOOOOO ECHOOOO
    ooo
    oo
    o
    .
    

    Python collects an arbitrary number of words into sys.argv, which is a list of strings that represents all inputs. Each word is considered a new argument when a whitespace character separates it from the others.

    By taking the code execution that handles user input and nesting it in the name-main idiom, you provide an additional entry point to your script.

    If you want to create an entry point for a package, then you should create a dedicated __main__.py file for that purpose. This file represents an entry point that Python invokes when you run your package using the -m option:

    When you create a virtual environment using the venv module, as shown above, then you run code defined in a __main__.py file. The -m option followed by the module name venv invokes __main__.py from the venv module.

    Because venv is a package rather than a small command-line interface (CLI) script, it has a dedicated __main__.py file as its entry point.

    In the wild, you may encounter many more reasons for using the name-main idiom in Python code. However, collecting user input, either through standard input or the command-line, is the primary suggested reason for using it.

    When Should You Avoid the Name-Main Idiom?

    Now that you’ve learned when to use the name-main idiom, it’s time to find out when it’s not the best idea to use it. You may be surprised to learn that in many cases, there are better options than nesting your code under if __name__ == "__main__" in Python.

    Sometimes, developers use the name-main idiom to add test runs to a script that combines code functionality and tests in the same file:

    # adder.py
    
    import unittest
    
    def add(a: int, b: int) -> int:
        return a + b
    
    class TestAdder(unittest.TestCase):
        def test_add_adds_two_numbers(self):
            self.assertEqual(add(1, 2), 3)
    
    if __name__ == "__main__":
        unittest.main()
    

    With this setup, you can run tests against your code when you execute it as a script:

    $ python adder.py
    .
    ----------------------------------------------------------------------
    Ran 1 test in 0.000s
    
    OK
    

    Because you ran the file as a script, __name__ was equal to "__main__", the conditional expression returned True, and Python called unittest.main(). The tiny test suite ran, and your test succeeded.

    At the same time, you didn’t create any unexpected code execution when importing your code as a module:

    >>>

    >>> import adder
    >>> adder.add(1, 2)
    3
    

    It’s still possible to import the module and use the function that you’ve defined there. The unit test won’t run unless you execute the module in the top-level code environment.

    While this works for small files, it’s generally not considered good practice. It’s not advised to mix tests and code in the same file. Instead, write your tests in a separate file. Following this advice generally makes for a more organized code base. This approach also removes any overhead, such as the need to import unittest in your main script file.

    Another reason that some programmers use the name-main idiom is to include a demonstration of what their code can do:

    # echo_demo.py
    
    def echo(text: str, repetitions: int = 3) -> str:
        """Imitate a real-world echo."""
        echoed_text = ""
        for i in range(repetitions, 0, -1):
            echoed_text += f"{text[-i:]}\n"
        return f"{echoed_text.lower()}."
    
    if __name__ == "__main__":
        print('Example call: echo("HELLO", repetitions=2)', end=f"\n{'-' * 42}\n")
        print(echo("HELLO", repetitions=2))
    

    Again, your users can still import the module without any side effects. Additionally, when they run echo_demo.py as a script, they get a peek at its functionality:

    $ python echo_demo.py
    Example call: echo("HELLO", repetitions=2)
    ------------------------------------------
    lo
    o
    .
    

    You may find such demo code executions in the name-main idiom, but there are arguably much better ways to demonstrate how to use your program. You can write detailed docstrings with example runs that can double as doctests, and you can compose proper documentation for your project.

    The previous two examples cover two common suboptimal use cases of the name-main idiom. There are also other scenarios when it’s best to avoid the name-main idiom in Python:

    • A pure script: If you write a script that’s meant to be run as a script, then you can put your code execution into the global namespace without nesting it in the name-main idiom. You can use Python as a scripting language because it doesn’t enforce strong object-oriented patterns. You don’t have to stick to design patterns from other languages when you program in Python.

    • A complex command-line program: If you write a larger command-line application, then it’s best to create a separate file as your entry point. You then import the code from your module there instead of handling user input with the name-main idiom. For more complex command-line programs, you’ll also benefit from using the built-in argparse module instead of sys.argv.

    Maybe you’ve used the name-main idiom for one of these suboptimal purposes before. If you want to learn more about how to write more idiomatic Python for each of these scenarios, then follow the provided links:

    Even though you now know when to avoid the name-main idiom, you might still wonder about how to best use it in a valid scenario.

    In What Way Should You Include the Name-Main Idiom?

    The name-main idiom in Python is just a conditional statement, so you could use it anywhere in your file—even more than once! For most use cases, however, you’ll put one name-main idiom at the bottom of your script:

    # All your code
    
    if __name__ == "__main__":
        ...
    

    You put the name-main idiom at the end of your script because the entry point for a Python script is always the top of the file. If you put the name-main idiom at the bottom of your file, then all your functions and classes get defined before Python evaluates the conditional expression.

    However, although it’s uncommon to use more than one name-main idiom in a script, there may be a reason to do so in some cases. Python’s style guide document, PEP 8, is clear about where to put all your import statements:

    Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. (Source)

    This is why you imported sys at the top of the file in echo.py:

    # echo.py
    
    import sys
    
    def echo(text: str, repetitions: int = 3) -> str:
        """Imitate a real-world echo."""
        echoed_text = ""
        for i in range(repetitions, 0, -1):
            echoed_text += f"{text[-i:]}\n"
        return f"{echoed_text.lower()}."
    
    if __name__ == "__main__":
        text = " ".join(sys.argv[1:])
        print(echo(text))
    

    However, you don’t even need to import sys at all when you simply want to import echo as a module.

    To address this and still stick with the style suggestions defined in PEP 8, you could use a second name-main idiom. By nesting the import of sys in a name-main idiom, you can keep all imports at the top of the file but avoid importing sys when you won’t need to use it:

    # echo.py
    
    if __name__ == "__main__":
        import sys
    
    def echo(text: str, repetitions: int = 3) -> str:
        """Imitate a real-world echo."""
        echoed_text = ""
        for i in range(repetitions, 0, -1):
            echoed_text += f"{text[-i:]}\n"
        return f"{echoed_text.lower()}."
    
    if __name__ == "__main__":
        text = " ".join(sys.argv[1:])
        print(echo(text))
    

    You nested the import of sys under another name-main idiom. That way, you keep the import statement at the top of your file, but you avoid importing sys when you use echo as a module.

    As you learned earlier in the tutorial, there are fewer occasions to use the name-main idiom than you might expect. For most of those use cases, putting one of these conditional checks at the bottom of your script will be your best choice.

    Finally, you may wonder what code should go into the conditional code block. The Python documentation offers clear guidance about the idiomatic usage of the name-main idiom in that regard:

    Putting as few statements as possible in the block below if __name___ == '__main__' can improve code clarity and correctness. (Source)

    Keep the code under your name-main idiom to a minimum! When you start putting multiple lines of code nested under the name-main idiom, then you should instead define a main() function and call that function:

    # echo.py
    
    import sys
    
    def echo(text: str, repetitions: int = 3) -> str:
        """Imitate a real-world echo."""
        echoed_text = ""
        for i in range(repetitions, 0, -1):
            echoed_text += f"{text[-i:]}\n"
        return f"{echoed_text.lower()}."
    
    def main() -> None:
        text = " ".join(sys.argv[1:])
        print(echo(text))
    
    if __name__ == "__main__":
        main()
    

    This design pattern gives you the advantage that the code under the name-main idiom is clear and concise. Additionally, it makes it possible to call main() even if you’ve imported your code as a module, for example to unit test its functions.

    In this section, you’ve learned that you should probably write the name-main idiom at the bottom of your script.

    If you have multiple lines of code that you’re planning to nest under if __name__ == "__main__", then it’s better to refactor that code into a main() function that you call from the conditional block under the name-main idiom.

    Now that you know how you can use the name-main idiom, you may wonder why it looks more cryptic than other Python code that you’re used to.

    Is the Idiom Boilerplate Code That Should Be Simplified?

    If you’re coming from a different object-oriented programming language, you might think that Python’s name-main idiom is an entry point akin to the main() functions in Java or C, but clumsier:

    The Power Rangers and Teletubby meme with text about main functions and Python's if __name__ equal to "__main__"

    Meme based on a web comic (Image: Mike Organisciak)

    While definitely funny and relatable, this meme is misleading because it implies that the name-main idiom is comparable to main() entry point functions in other languages.

    Python’s name-main idiom isn’t special. It’s just a conditional check. It may look cryptic at first, especially when you’re starting to work with Python and you’re used to Python’s slim and elegant syntax. After all, the name-main idiom includes a dunder variable from the global namespace, and a string that’s a dunder value as well.

    So it’s not the type of entry point that main represents in other languages. But why does it look the way it does? You may have copied and pasted the idiom many times, or even typed it out, and wondered why Python doesn’t have a more concise syntax for it.

    If you browse the archives of the Python-ideas mailing list, rejected PEPs, and the Python discussion forum, then you’ll find a number of attempts to change the idiom.

    If you read some of these discussions, then you’ll notice that many seasoned Pythonistas argue that the idiom isn’t cryptic and shouldn’t be changed. They give multiple reasons:

    • It’s short: Most suggested changes save only two lines of code.
    • It has a limited use case: You should only use it if you need to run a file both as a module as well as a script. You shouldn’t need to use it very often.
    • It exposes complexity: Dunder variables and function are a big part of Python once you peek a bit deeper. That can make the current idiom an entry point for learners that sparks curiosity and gives them a first look under the hood of Python’s syntax.
    • It maintains backward compatibility: The name-main idiom has been a de facto standard in the language for a long time, which means that changing it would break backward compatibility.

    Okay, so you’re stuck with if __name__ == "__main__" for the time being. It seems like it’d be helpful to find a good way to refer to it consistently and concisely!

    Expand the section below for a bit of context and a few suggestions on how you could talk about the name-main idiom without twisting your tongue or knotting your fingers:

    You’ll probably discuss using the name-main idiom at some point in your Python career. It’s a long expression to write and even more cumbersome to say out loud, so you might as well find a good way to talk about it.

    There are different ways to refer to it in the Python community. Most mentions online include the whole if __name__ == "__main__" expression followed by a word:

    • The if __name__ == "__main__" convention (Source)
    • The if __name__ == "__main__" expression (Source)
    • The if __name__ ... idiom (Source)
    • The if __name__ == "__main__": ... idiom (Source)
    • The if __name__ == "__main__" idiom (Source)
    • The executable stanza (Source)

    As you may notice, there’s no strict convention around how to talk about if __name__ == "__main__", but you probably won’t do wrong if you follow the general consensus of calling it the if __name__ == "__main__" idiom.

    If you want to promote standardizing a shorter name for the idiom, then tell your friends to call it the name-main idiom. That’s what we’ll be calling it at Real Python! If you find the term useful, then maybe it’ll catch on.

    If you’re curious, take a plunge into some of the linked discussions in the various Python community channels to learn more about why developers argue for keeping the name-main idiom as it is.

    Conclusion

    You’ve learned what the if __name__ == "__main__" idiom does in Python. It allows you to write code that executes when you run the file as a script, but not when you import it as a module. It’s best to use it when you want to collect user input during a script run and avoid side effects when importing your module—for example, to unit test its functions.

    You also got to know some common but suboptimal use cases and learned about better and more idiomatic approaches that you can take in those scenarios. Maybe you’ve accepted Python’s name-main idiom after learning more about it, but if you still dislike it, then it’s good to know that you can probably replace its use in most cases.

    When do you use the name-main idiom in your Python code? While reading this tutorial, did you discover a way to replace it, or is there a good use case that we missed? Share your thoughts in the comments below.

    Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: What Does if __name__ == «__main__» Mean in Python?

    Понравилась статья? Поделить с друзьями:
  • Illegal new face 3d max ошибка
  • Import seaborn as sns ошибка
  • Immobilizer see manual volvo xc90 как сбросить ошибку
  • Iis журнал ошибок
  • Import requests python ошибка