Skip to content

What is __name__?

Before we write the Flask app, there is one Python concept you need to understand properly — __name__. It is small, it is clever, and it shows up in every Flask app you will ever write.


Every Python file has it

Python automatically creates a variable called __name__ in every single .py file. You did not write it. Python put it there. It is always there whether you use it or not.

Let's see what it contains. Create a new file called test.py and put just this in it:

print(__name__)

Run it:

python test.py

You will see:

__main__

Python set __name__ to the string "__main__". That is what it does when you run a file directly — it sets __name__ to "__main__" as Python's way of marking: this is the file that was launched.


What changes when you import a file?

Now imagine you have two files — test.py and runner.py.

test.py:

print(__name__)

runner.py:

import test

Run runner.py. What prints?

test

Not "__main__" this time — the file's own name. When a file is imported by another file, Python sets its __name__ to the file's name instead.

So __name__ answers the question: was this file run directly, or was it imported by someone else?

  • Run directly → __name__ is "__main__"
  • Imported → __name__ is the file's name

Playing with it using if

You already know if statements. Let's use one with __name__ and see what happens.

In test.py, try this:

print("My name is:", __name__)

if __name__ == "banana":
    print("I am a banana. This will never run.")

if __name__ == "test":
    print("I am being imported as 'test'.")

if __name__ == "__main__":
    print("I was run directly!")

Run test.py directly. You will see:

My name is: __main__
I was run directly!

The first two if blocks are skipped — __name__ is neither "banana" nor "test" when you run the file directly.

Now run it from runner.py using import test. You will see:

My name is: test
I am being imported as 'test'.

The last if is skipped this time because __name__ is "test", not "__main__".


Why this matters for Flask

In your Flask app, you will write:

if __name__ == '__main__':
    app.run(debug=True)

This says: only start the server if this file was run directly.

Why does this matter? Because later, when your project grows, other files might import app.py to use things from it. You do not want the server to accidentally start every time that happens. The if __name__ check ensures the server only starts when you intentionally run app.py directly.

One small check. Very important habit.


Challenge

In test.py, write a few more if statements checking __name__ against things it could never be — your name, a random word, a number as a string. Run it and confirm only the __main__ block fires.

Then create runner.py, import test, and run runner.py instead. Which block fires now? Make sure you can explain why before moving on.


← The Project Structure    Next: Your First Flask App →