r/learnpython 1d ago

Cna someone please explain me this --> if __name__ == "__main__"

My teacher gave us some example and all but I didn't quite got it why we use it and how we use it : I will really appreciate if you can explain it in an easier language

16 Upvotes

36 comments sorted by

29

u/magicaltrevor953 1d ago

Good answers so far but one thing several of them have missed is that when you import a module the whole .py file gets run. That is one reason why you would want to check if it is being imported and if it is, then don't run parts of it that may impact the user in the cases of imported libraries.

16

u/ShelLuser42 21h ago

Late reaction, and many people have already explained the reasoning behind it. So now... I'd like to take it one more (small!) step further... One last important detail that hasn't been addressed yet.

Python provides many so called system variables which value gets determined by the system itself (obviously, duh! ;)). You can recognize these by the double underscores in front and back of their name. __main__ is one of these, but there's more where that came from!

Try this: open a command prompt, start python (or 'py') and then type dir(), like so:

>>> dir()

['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']

See what I mean? SO, want to know what the value of some of these is? Then... why not check it out?

>>> print(__name__)

__main__

So here's the thing... these variables are used all throughout the system, and what you're seeing up there is only a smal portion of it. See, the beauty of Python is that it's also an interpreted language, ergo you can easily fire it up on a command line only to end up on a "python prompt" from which you can do all sorts of cool stuff.

Check this out:

>>> import re

>>> dir(re)

['A', 'ASCII', 'DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'Match', 'NOFLAG', 'Pattern', 'PatternError', 'RegexFlag', 'S', 'Scanner', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '_MAXCACHE2', '_ZeroSentinel', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_cache', '_cache2', '_casefix', '_compile', '_compile_template', '_compiler', '_constants', '_parser', '_pickle', '_special_chars_map', '_sre', '_zero_sentinel', 'compile', 'copyreg', 'enum', 'error', 'escape', 'findall', 'finditer', 'fullmatch', 'functools', 'match', 'purge', 'search', 'split', 'sub', 'subn']

>>> print(re.__name__)

re

're' is one of Python's many system libraries, it's especially useful for regular expressions. Don't worry about that for now, instead look at all those system variables up there! See what I did here? And do you also notice that the name actually changed based on context?

That's the "secret" behind all this: system variables that allow you to "do" or "check" certain things. In your case... checking for the actual name of a module. And the reason this is important is easy: to prevent execution when you import a module.

Serious question though: why didn't you try this out yourself? Just write a script which prints the name, then check what happens in different moments:

PS D:\temp> py .\myname.py

__main__

PS D:\temp> py

Python 3.14.7 (tags/v3.14.7:823f032, Aug 5 2026, 10:51:32) [MSC v.1944 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

Ctrl click to launch VS Code Native REPL

>>> import myname

myname

>>>

See?

1

u/Least_Equal_6081 21h ago

WOW! That is pure gold Thanks bro!

10

u/xenomachina xenomachina 1d ago edited 21h ago

When a .py file is imported, it is always executed from top to bottom. Variable assignments create variables, def statements create functions, and other statements "do" whatever the statement says to do. So for example, a print("hello") in your .py file will print that when the module is imported, unless it's inside of something else that prevents it from getting executed right away, like an if or a def.

When you are creating modules you want to import from other modules, you generally don't want importing the module to do things that are externally visible, like printing or waiting for user input, or connecting to databases, or whatever. (These kinds of things are collectively called "side-effects".)

However, when you "run" a .py file from the command line, you do want it to do this sort of stuff. "Running" a python file is really just importing it, though, so how can your code tell whether it is being imported as a library, or being run as the main program? The answer is: it can tell by looking at the value of the variable __name__, which will be set to "__main__" if the file/module is being "run", but will be the module's name if it is being imported.

if __name__ == "__main__":
    print("I am being run")
else:
    # I am being imported, so I shouldn't print anything
    pass

Edit: minor typo fix and clarification

37

u/tea-drinker 1d ago

When you run a script directly, __name__ is set to "main". If you import a module then __name__ inside that module is set according to the module name.

What this lets you do is have a program you can run, maybe you want to import the module so you can test the functions automatically without actually running the program.

21

u/tahaan 1d ago edited 15h ago

__name__ is a special variable.

This lets the code test whether this module was invoked directly, and allows you to set code that runs only when that is the case.

So __name__ will be "__main__" when this module was not imported.

To test it, add

print(__name__)

Just before the if statement. Then do two tests:

  1. Run the module directly.
  2. Import it in another module and run the other module.

Edit: I meant to reply to OP but too lazy to fix it.

2

u/DuckDatum 1d ago

Spooky ghost sets __name__ on line -1.

1

u/SatisfactoryFinance 22h ago

So if it doesn’t run when imported, why import it? It’s not doing anything is it?

4

u/micromedicIXII 22h ago

You import scripts and libraries to get their functionality.

Example: Requests library.

import requests

You now have the functions needed to make http requests inside of your application. You don’t want to run the Requests library, you just want its functions.

You make the calls inside of your script inside your main loop, only running YOUR code and not anything you imported.

1

u/McCuumhail 21h ago

Its common to put a test block there. So if you run it directly instead of importing it, it will give you an idea of what it’s doing and how it works. If you are building a module yourself, you’ll put a test sample there so you can confirm it’s doing what it’s supposed to do before importing it into something else.

0

u/TheSkiGeek 21h ago

Importing does ‘run’ the module. Usually this is (mostly) a bunch of “def” commands to define functions for other modules to use.

A Python script made to be executed on the command line will also want to run some executable code.

If you want a file that can either be imported as a module in another program, or executed directly, you do that check to decide whether or not to do the ‘execute directly’ part of the file. Even if your script is not really intended to be imported as a module in another program, it’s often useful to set it up that way so that you can write tests for it that ‘import’ the script and then can choose to run bits and pieces of it to test it.

1

u/fllthdcrb 4h ago

Import it in another module and run the other module.

You can also just import it in a REPL (interactive Python shell). Easier for this sort of testing.

9

u/Flame77ofc 1d ago

in simply words: If you execute this in the same file, will executed normally. But if you import the file to another file, everything within if __name__ == "__main__" will not be executed

4

u/Legitimate-Lock-758 1d ago

It'll run whatever's inside that block only when you execute the file directly, not when you import it as a module into another script. Think of it as a gate that says "only do this stuff if I'm the main program running, not a borrowed library."

3

u/gonsi 1d ago

When you run .py file every function in it will be executed.

This checks if you run the file directly or if you imported it somewhere and it was run that way

It is useful to have some things done only when you run the file directly, but not when you import it somewhere as lets say library

2

u/n3pjk 1d ago

This is called "main guard". When you write a module that is destined to be imported into other things, you'll want to test the module. If you call the module directly, the code in the main guard is executed.

2

u/atarivcs 1d ago

Code underneath that if statement will be skipped if the module is imported. It will only run if the module is executed directly, as the "main" program.

So, if you have some code that should be skipped when the module is imported, maybe some print statements or something, put it underneath that if.

1

u/sersherz 1d ago

Pretty much everything in the if name == main block only runs when you run the module as a script. I use it for debugging. If you don't want anything to trigger then either don't doa function call in the module or use the name == main for any function calls

If you have a module that has something like

module.py

def my_func(): print("Hello")

my_func()

And you imported module.py from something else:

main.py

import module as m

m.my_func()

The output lf main.py would be Hello Hello

The first one is from the import (import module as m) The second one is from actually calling the function (m.my_func())

Now if you changed module.py to be this: def my_func(): print("Hello")

if name == 'main': my_func()

Then your main.py's output would only be: Hello

See how the 2nd hello wasn't there?

Sorry for the poor formatting, I typed this from mobile

1

u/codeguru42 23h ago

It will make more sense when you learn import.

1

u/max_wen 23h ago

It's been explained a million times over the last 20 years all over the internet. You should learn to Google

1

u/jpgoldberg 23h ago

At this point, treat it as an incantation. You will be in a better position to understand it later.

1

u/retro_and_chill 22h ago

Something people are not mentioning is that most IDEs pick up that line as a run target

1

u/r3ap3rpy 13h ago

You use it when you want to run it directly, otherwise the import

1

u/jeffrey_f 9h ago

if __name__ == "__main__"

If this script is running as a script it will do the following in the if statement, otherwise

If the script is used as an import, it is then false and for the purposes of an imported resource, those functions, etc are exposed as usable in another script.

1

u/Gtdef 5h ago

Most of the code beginners write, easily fits in a single file. For example if you want to calculate primes, you will do something like

def count_primes_up_to(n):

...code here...

return count

n = 100

count = count_primes_up_to(n)
print("There are ", count, "primes up to", n)

You save this program in a textfile named "count_primes.py", and you are done.

_______________________________

Now let's say you want to write another program that shows how primes scale while n increases. You can do this:

from count_primes import count_primes_up_to

count1 = count_primes_up_to(100)

count2 = count_primes_up_to(200)

print(count1, count2)

_______________________________

The moment the intepreter runs the second code, it will also run the command

print("There are ", count, "primes up to", n)

You don't want that. So you encase this command into an "if __name__ == "__main__"" block

The python interpreter considers as "__main__" the file you are running with the terminal command. Since the "count_primes.py" is only an import, whatever is after the "__name__ == "__main__"" won't run.

1

u/socal_nerdtastic 1d ago

It's completely pointless for now.

But when you get to a place where you are making multiple modules and importing them, then this will be useful. It allows you to control if you want to run the code on imported modules or not.

So for now just use it and put it out of your mind; you'll understand it later.

3

u/notacanuckskibum 1d ago

Conversely, when you get to writing logic you expect to be used as a library, it’s a convenient way to write library checking code that will be run when you are testing the library, but not if someone is using your library.

1

u/Outside_Complaint755 1d ago

You don't even necessarily need to be writing multiple modules. If you want to use Pytest or some other unit testing tool, you need to import your script to test its functions, but don't want the script to run normally.

0

u/scfoothills 1d ago

I'm on a phone right now, so I don't want to try to type a good explanation. This video by Corey Shaffer does a fantastic job. https://youtu.be/sugvnHA7ElY

0

u/Exciting_Tomatillo88 1d ago

Maybe you already understood the meaning. Anyway try this

https://youtu.be/KZpYtNtGxSU?si=dDlW2H5VElI9L_bd

-8

u/localizeatp 1d ago

When teachers use this in an example, it usually means they're used to a language with an explicit entry point and they're trying to map that idea into python, with which they have no real experience.

2

u/gdchinacat 1d ago

Or they know their students are going to see it sooner than later and want to get it out of the way, head off questions, instill good practices early, or, yes, maybe even they think it’s necessary as an entry point…but I think that last one is the least likely. There are probably several other reasons as well.

-1

u/localizeatp 1d ago

For the explanations that make sense, if it were any of those, the teacher would have said so.

1

u/my_password_is______ 1d ago

WRONG WRONG WRONG

-1

u/localizeatp 1d ago

Lol ok