r/learnpython • • 8d ago

Basically, if main

In Python, when you run your program in another folder, we add this, but I don't understand why. What's the point of doing this? If someone could explain it in a simplified way, I'd appreciate it.

10 Upvotes

27 comments sorted by

View all comments

1

u/TheRNGuy 7d ago edited 7d ago

It means: run this code only when the file is launched directly, not when it is imported by another Python file. 

python my_program.py will run that code,

import my_program won't run that code.

If this is a file for imports (you're making a library), then do not add it.

You usually use it in dev servers or small scripts that you directly run from console.

You won't need to write it in Flask, FastAPI, SideFx Houdini, etc.