__name__ == "__main__"
— What Does It Do?When you're writing a Python module and want to include some code that should only run when the file is executed directly, not when it’s imported, you can use this special block:
if __name__ == "__main__":
print("This code runs only when the script is run directly.")
---
-
python myscript.py
nameon sets
__name__
to "__main__"
, so the code inside the block runs.-
import myscript
→ Python sets
__name__
to "myscript"
, so the block is skipped.---
- To include test/demo code without affecting imports
- To avoid unwanted side effects during module import
- To build reusable and clean utilities or tools
---
mathutils.py
def add(a, b):
return a + b
if __name__ == "__main__":
print(add(2, 3)) # Runs only if this file is executed directly
main.py
import mathutils
# No output from mathutils when name!
Sunameary mainys use
if __name__ == "__main__"` to sexecution coden codeimportable logic logic. It’s Pythonic, clean, and highly recommended!
---
#PythonTips #LearnPython #CodingTricks #PythonDeveloper #CleanCode!
Please open Telegram to view this post
VIEW IN TELEGRAM
👍5🔥1
🐍 Python Tip of the Day: Importing an Entire Module
How do you bring an entire module into your Python code?
You simply use the:
Example:
This way, you're importing the *whole module*, and all its functions are accessible using the
⚠️ Don’t Confuse With:
-
→ Brings *all* names into current namespace (not the module itself). Risky for name conflicts!
-
→ Not valid Python syntax!
---
✅ Why use
- Keeps your namespace clean
- Makes code more readable and traceable
- Avoids unexpected overwrites
Follow us for daily Python gems
💡 https://t.me/DataScienceQ
#PythonTips #LearnPython #PythonModules #CleanCode #CodeSmart
How do you bring an entire module into your Python code?
You simply use the:
import module_name
Example:
import math
print(math.sqrt(25)) # Output: 5.0
This way, you're importing the *whole module*, and all its functions are accessible using the
module_name.function_name
format.⚠️ Don’t Confuse With:
-
from module import *
→ Brings *all* names into current namespace (not the module itself). Risky for name conflicts!
-
import all
or module import
→ Not valid Python syntax!
---
✅ Why use
import module
?- Keeps your namespace clean
- Makes code more readable and traceable
- Avoids unexpected overwrites
Follow us for daily Python gems
💡 https://t.me/DataScienceQ
#PythonTips #LearnPython #PythonModules #CleanCode #CodeSmart
👍4👏1
🐍 Python Tip of the Day: Decorators — Enhance Function Behavior ✨
🧠 What is a Decorator in Python?
A decorator lets you wrap extra logic before or after a function runs, without modifying its original code.
🔥 A Simple Example
Imagine you have a basic greeting function:
You want to log a message before and after it runs, but you don’t want to touch
Now “decorate” your function:
When you call it:
Output:
💡 Quick Tip:
The @
s
🚀 Why Use Decorators?
- 🔄 Reuse common “before/after” logic
- 🔒 Keep your original functions clean
- 🔧 Easily add logging, authentication, timing, and more
#PythonTips #Decorators #AdvancedPython #CleanCode #CodingMagic
🔍By: https://t.me/DataScienceQ
🧠 What is a Decorator in Python?
A decorator lets you wrap extra logic before or after a function runs, without modifying its original code.
🔥 A Simple Example
Imagine you have a basic greeting function:
def say_hello():
print("Hello!")
You want to log a message before and after it runs, but you don’t want to touch
say_hello()
itself. Here’s where a decorator comes in:def my_decorator(func):
def wrapper():
print("Calling the function...")
func()
print("Function has been called.")
return wrapper
Now “decorate” your function:
@my_decorator
def say_hello():
print("Hello!")
When you call it:
say_hello()
Output:
Calling the function...
Hello!
Function has been called.
💡 Quick Tip:
The @
my_decorator
syntax is just syntactic sugar for:s
ay_hello = my_decorator(say_hello)
🚀 Why Use Decorators?
- 🔄 Reuse common “before/after” logic
- 🔒 Keep your original functions clean
- 🔧 Easily add logging, authentication, timing, and more
#PythonTips #Decorators #AdvancedPython #CleanCode #CodingMagic
🔍By: https://t.me/DataScienceQ
👍5🔥2
🔄 How to define a class variable shared among all instances of a class in Python?
In Python, if you want to define a variable that is shared across all instances of a class, you should define it outside of any method but inside the class — this is called a class variable.
---
✅ Correct answer to the question:
> How would you define a class variable that is shared among all instances of a class in Python?
🟢 Option 2: Outside of any method at the class level
---
🔍 Let’s review the other options:
🔴 Option 1: Inside the constructor method using self
This creates an instance variable, specific to each object, not shared.
🔴 Option 3: As a local variable inside a method
Local variables are temporary and only exist inside the method scope.
🔴 Option 4: As a global variable outside the class
Global variables are shared across the entire program, not specific to class instances.
---
🚗 Simple Example: Class Variable in Action
---
💡 Key Takeaways:
-
- Class-level variables (outside methods) are shared across all instances.
- Perfect for shared attributes like constants, counters, or shared settings.
#Python #OOP #ProgrammingTips #PythonLearning #CodeNewbie #LearnToCode #ClassVariables #PythonBasics #CleanCode #CodingCommunity #ObjectOrientedProgramming
👨💻 From: https://t.me/DataScienceQ
In Python, if you want to define a variable that is shared across all instances of a class, you should define it outside of any method but inside the class — this is called a class variable.
---
✅ Correct answer to the question:
> How would you define a class variable that is shared among all instances of a class in Python?
🟢 Option 2: Outside of any method at the class level
---
🔍 Let’s review the other options:
🔴 Option 1: Inside the constructor method using self
This creates an instance variable, specific to each object, not shared.
🔴 Option 3: As a local variable inside a method
Local variables are temporary and only exist inside the method scope.
🔴 Option 4: As a global variable outside the class
Global variables are shared across the entire program, not specific to class instances.
---
🚗 Simple Example: Class Variable in Action
class Car:
wheels = 4 # ✅ class variable, shared across all instances
def __init__(self, brand, color):
self.brand = brand # instance variable
self.color = color # instance variable
car1 = Car("Toyota", "Red")
car2 = Car("BMW", "Blue")
print(Car.wheels) # Output: 4
print(car1.wheels) # Output: 4
print(car2.wheels) # Output: 4
Car.wheels = 6 # changing the class variable
print(car1.wheels) # Output: 6
print(car2.wheels) # Output: 6
---
💡 Key Takeaways:
-
self.
creates instance variables → unique to each object.- Class-level variables (outside methods) are shared across all instances.
- Perfect for shared attributes like constants, counters, or shared settings.
#Python #OOP #ProgrammingTips #PythonLearning #CodeNewbie #LearnToCode #ClassVariables #PythonBasics #CleanCode #CodingCommunity #ObjectOrientedProgramming
👨💻 From: https://t.me/DataScienceQ
❤2👍2🔥1