Some text some message..
Back 🔹Dunder Variables in Python 26 Jul, 2025

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.


🔹 1. What are Dunder Variables?

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.


🔹 2. Common Dunder Variables

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.

🔹 3. Common Dunder Methods

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.

🔸 Example: __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.


🔸 Example: Custom __str__ Method

class 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

🧠 Tip:

Never name your own variables or functions with leading/trailing double underscores. These are reserved for Python's internal use.