Skip to Content
Course content

158: The __name__ == '__main__' Idiom

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you bought a high-end espresso machine. When you first take it out of the box and plug it in, it might run a "First-Time Setup" sequence—flushing the pipes, heating the boiler, and blinking a few lights to tell you it's ready. That sequence is great for the first time you use the machine independently. But imagine if you decided to integrate that espresso machine into a massive, automated coffee kiosk. You wouldn't want the machine to run its entire "First-Time Setup" every single time the kiosk's main computer sends a command to brew a latte. You just want the machine to brew the coffee.

In Python, the __name__ == '__main__' idiom is exactly like that "First-Time Setup" sequence. It allows you to write a file that can act as both a reusable tool (a module) and a standalone program (a script), without the two roles clashing.

The Script vs. The Module Dilemma

Up until now, you've likely been writing scripts that you run directly. You hit "Run" or type python my_script.py in your terminal, and the code executes from top to bottom. But as your projects grow, you'll start moving functions into separate files so you can reuse them across different parts of your app. This is where things get messy.

When Python imports a file, it doesn't just "look" at the functions inside; it actually executes the entire file from top to bottom. If you have a print statement or a function call sitting out in the open at the bottom of your file for testing purposes, that code will run every single time you import that file into another script. I can't tell you how many times I've seen a developer accidentally trigger a database wipe or a thousand-line test log just because they imported a utility file that had "test code" left at the bottom.

How Python Labels Your Code

Python handles this by assigning a special built-in variable called __name__ to every module. The value of this variable depends on how the file is being executed:

  • Running it directly: If you run python calculator.py, Python sets __name__ to the string "__main__".
  • Importing it: If you are in a different file and write import calculator, Python sets the __name__ inside calculator.py to the actual filename: "calculator".

By wrapping your "execution code" in an if __name__ == "__main__": block, you're essentially telling Python: "Only do this if I ran this specific file directly. If someone is just importing me to use my functions, keep quiet and stay out of the way."

Putting Guardrails Around Your Execution

Let's look at a real example. Suppose we have a file called password_validator.py. We want this file to be a library that other scripts can use to check passwords, but we also want to be able to run it quickly to test if our validation logic is working.

def is_strong(password):
    # A simple check for length and digits
    return len(password) >= 8 and any(char.isdigit() for char in password)

# This is the "Demo Mode" or "Setup Sequence"
if __name__ == "__main__":
    print("Running Password Validator Test Mode...")
    test_pass = input("Enter a password to test: ")
    if is_strong(test_pass):
        print("Strong password!")
    else:
        print("Too weak.")

Now, if you run python password_validator.py, you'll see the prompt to enter a password. It's acting as a standalone tool. However, if you create a new file called signup_form.py and write from password_validator import is_strong, the input() prompt will not appear. You get access to the is_strong function without the testing logic interfering with your signup form.

I usually recommend putting all your "runnable" logic inside a function called main() and then calling that inside the idiom block. It keeps the global scope clean and makes your code look professional.

def main():
    print("Executing main logic...")
    # Your actual program flow goes here

if __name__ == "__main__":
    main()



📋 Practical Task

Exercise: Building a Reusable Tax Calculator

Your goal is to create a tax calculation module that can be used by other programs but also has its own built-in testing suite that only runs when executed directly.

Requirements:

  1. Create a file named tax_utils.py.
  2. Inside tax_utils.py, define a function calculate_sales_tax(price, tax_rate) that returns the total price (price + tax).
  3. Implement the if __name__ == "__main__": idiom in tax_utils.py. Inside this block, write code that tests the function with a sample price of 100 and a tax rate of 0.07, printing the result to the console.
  4. Create a second file named invoice_gen.py. In this file, import calculate_sales_tax from tax_utils.py and call it once with any values you like, printing the result.

Verification:

  • Run python tax_utils.py. You should see your test result printed.
  • Run python invoice_gen.py. You should see the invoice result, but you should not see the "test" output from the tax_utils file.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.