__name__Easy Examples

The name of a module; equals '__main__' when run as a script

Accessing __name__

How to access and use __name__.

python
# __name__ holds the name of a module or class
print(__name__)

class MyClass:
    pass

print(MyClass.__name__)

def my_func():
    pass

print(my_func.__name__)

__name__ is a special attribute that the name of a module; equals '__main__' when run as a script.

__name__ in practice

Using __name__ in everyday code.

python
# More __name__ examples
print("__name__ is a special Python attribute")

# Every object has certain dunder attributes
obj = object()
attrs = [a for a in dir(obj) if a.startswith("__")]
print(f"object has {len(attrs)} dunder attributes")

Understanding __name__ helps you introspect and debug Python objects.

Want to try these examples interactively?

Open Easy Playground