Get the class name of a Python instance
Use type(obj).__name__ for an instance’s class name, and add the module and qualified name when a short name is ambiguous.
Use type(obj).__name__ to get the name of the class that created an instance:
class MyClass:
pass
obj = MyClass()
print(type(obj).__name__) # MyClass
print(obj.__class__.__name__) # MyClass for this ordinary instance
Both expressions agree for ordinary objects. A proxy or custom attribute implementation can report a different __class__, so type(obj) is preferable when you need the actual runtime type.
Include the enclosing class or module
class Outer:
class Inner:
pass
obj = Outer.Inner()
cls = type(obj)
print(cls.__qualname__) # Outer.Inner
print(cls.__module__) # __main__ when run as a script
print(f"{cls.__module__}.{cls.__qualname__}")
__qualname__ includes enclosing scopes. Classes defined inside functions can include <locals> in that name, so the result is useful identification text, not necessarily an importable path. Two modules can also define classes with the same short __name__.
Use a class name in logs
import logging
class Worker:
def __init__(self):
cls = type(self)
self.logger = logging.getLogger(
f"{cls.__module__}.{cls.__qualname__}"
)
This creates a class-oriented logger name without duplicating the class name as a string. A module-level logging.getLogger(__name__) is another common choice and often produces a simpler hierarchy. Keep logger names bounded; avoid creating a new name for every individual object or request.
For serialization, a class name can be a label, but it is not a stable schema identifier or a reason to import and execute arbitrary code supplied in input.
FAQ
How do I get the class itself? type(obj) returns the class object. Calling it constructs a new instance only if you supply the arguments its constructor requires; type(obj)() is not universally valid.
Does this work with built-in objects? Yes: type([]).__name__ is list, and type("").__name__ is str.
What if I already have the class? Read MyClass.__name__ directly. type(MyClass) asks for its metaclass instead.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan