Q&A library Python

What does if __name__ == "__main__" do in Python?

Python Beginner importsmodulesscripts

Short answer

It runs a block only when the file is executed directly, not when it is imported. This lets a file work both as a runnable script and as an importable module without side effects.

The short version

The block under if __name__ == "__main__": runs only when you execute the file directly. When another file imports it instead, the block is skipped. This lets a single file serve as both a runnable script and an importable library of functions, without the script part firing during import.

What name actually is

Every module has a __name__ variable. When you run a file directly with python myfile.py, Python sets its __name__ to the string "__main__". When the same file is imported, __name__ is set to the module's name instead, for example "myfile". The if simply checks which situation you are in.

A worked example

# greet.py
def greeting(name):
    return f"Hello, {name}"

if __name__ == "__main__":
    print(greeting("world"))

Run it directly and it prints Hello, world. Import it elsewhere and nothing prints, but greeting is available to call.

# other.py
from greet import greeting
print(greeting("Ana"))   # uses the function, no stray output

The problem it solves

Without the guard, any top-level code runs the moment the file is imported. So if greet.py ended with a bare print(greeting("world")), then importing it just to reuse greeting would also print "Hello, world" as an unwanted side effect. Worse, code that reads files or starts a long process would run during import. The guard keeps the "run me" part separate from the "import my functions" part.

A common misunderstanding

The line is not magic and not required. A file with no such guard still runs fine directly. The guard only matters when a file might be both imported and run. It is also not a function or a special keyword: __name__ is an ordinary variable, and you could print it to see its value.

The usual pattern

Many projects put the real work in a main function and call it under the guard, which keeps the entry point tidy and testable.

def main():
    print(greeting("world"))

if __name__ == "__main__":
    main()

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project