Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
158: The __name__ == '__main__' Idiom
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__insidecalculator.pyto 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:
- Create a file named
tax_utils.py. - Inside
tax_utils.py, define a functioncalculate_sales_tax(price, tax_rate)that returns the total price (price + tax). - Implement the
if __name__ == "__main__":idiom intax_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. - Create a second file named
invoice_gen.py. In this file, importcalculate_sales_taxfromtax_utils.pyand 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 thetax_utilsfile.
There are no comments for now.