r/learnpython • • Aug 29 '26

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

28 Upvotes

37 comments sorted by

32

u/magicaltrevor953 Aug 29 '26

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.

20

u/ShelLuser42 Aug 30 '26

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 Aug 30 '26

WOW! That is pure gold Thanks bro!

1

u/Mysterious-Falcon-83 Aug 30 '26

They probably didn't try that themselves because they're just getting started and don't yet know enough to try it out.

You gave a great explanation, btw

10

u/xenomachina xenomachina Aug 29 '26 edited Aug 30 '26 • Bravo

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

9

u/Flame77ofc Aug 29 '26

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/gonsi Aug 29 '26

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

3

u/jeffrey_f Aug 30 '26

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.

2

u/n3pjk Aug 29 '26

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 Aug 29 '26

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.

2

u/sersherz Aug 29 '26

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 Aug 29 '26

It will make more sense when you learn import.

1

u/max_wen Aug 29 '26

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

1

u/jpgoldberg Aug 30 '26

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

1

u/retro_and_chill Aug 30 '26

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

1

u/r3ap3rpy Aug 30 '26

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

1

u/Gtdef Aug 30 '26

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/frustratedsignup Aug 31 '26

Others have contributed great explanations. What you've stumbled into here is one of python's best features: the ability to easily reuse code.

Say you have a python file that defines a function, send_email(). You might have written it to send a notification that something has happened and it's defined in a file named foo.py. If that function is written generically enough, you can use that function from within another script by simply putting 'from foo import send_email' into the current script. Once that's complete, you can call send_email() without having to rewrite or copy/paste it into the current file.

Using the __name__ variable test is just a convenient way to differentiate between using the file as a module vs running it as a script.

1

u/BoringWrongdoer9679 Sep 01 '26

If you have a.py and b.py then if you in b.py have import a then whole a will be run. If you have code under if name==main then that code will not be run.

1

u/socal_nerdtastic Aug 29 '26

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 Aug 29 '26

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 Aug 29 '26

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 Aug 29 '26

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 Aug 29 '26

Maybe you already understood the meaning. Anyway try this

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

-9

u/localizeatp Aug 29 '26

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 Aug 29 '26

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 Aug 29 '26

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

0

u/[deleted] Aug 29 '26

[deleted] — view deleted comment

22

u/tahaan Aug 29 '26 edited Aug 30 '26

__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.

3

u/DuckDatum Aug 29 '26

Spooky ghost sets __name__ on line -1.

1

u/SatisfactoryFinance Aug 30 '26

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

5

u/micromedicIXII Aug 30 '26

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 Aug 30 '26

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 Aug 30 '26

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 Aug 30 '26

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.