In Python, dunder variables (short for "double underscore"), are special variables or methods that start and end with double underscores, like __name__
, __init__
, __str__
, etc.
Dunder variables (also called magic or special variables/methods) are used internally by Python to implement certain behaviors or hooks. They are not meant to be defined arbitrarily, unless you know what you're doing.
Dunder Variable | Description |
---|---|
__name__ |
Tells whether the file is being run directly or imported as a module. |
__file__ |
The path of the file being executed. |
__doc__ |
Returns the docstring of a module, class, or function. |
__dict__ |
Returns a dictionary of the object’s attributes. |
__class__ |
Returns the class type of an instance. |
Dunder Method | Description |
---|---|
__init__() |
Constructor, used to initialize a new object. |
__str__() |
Returns a readable string representation of the object. |
__repr__() |
Returns an official string representation (for developers). |
__len__() |
Defines behavior for len(obj) . |
__getitem__() |
Used to access items via indexing. |
__name__
Usage# file: mymodule.py
def greet():
print("Hello!")
if __name__ == "__main__":
greet()
When run directly: __name__ == "__main__"
→ greet()
is called.
When imported: __name__ == "mymodule"
→ greet()
is not called.
__str__
Methodclass Dog:
def __init__(self, name):
self.name = name
def __str__(self):
return f"This is a dog named {self.name}"
d = Dog("Buddy")
print(d) # Output: This is a dog named Buddy
Never name your own variables or functions with leading/trailing double underscores. These are reserved for Python's internal use.