Access type(obj).__name__ (or obj.__class__.__name__) to retrieve the short class name as a string (e.g., "DataFrame"), or combine f"{type(obj).__module__}.{type(obj).__qualname__}" when you need the fully qualified module and nested class path (e.g., "pandas.core.frame.DataFrame").
Basic Example
class Outer:
class Inner:
pass
obj = Outer.Inner()
items = [1, 2, 3]
# 1. Recommended: type(obj).__name__ returns the exact class name as a string
print(type(obj).__name__) # Output: "Inner"
print(type(items).__name__) # Output: "list"
# 2. Equivalent attribute access on the instance
print(obj.__class__.__name__) # Output: "Inner"
# 3. Include nested enclosing class names (__qualname__) or full module path (__module__)
print(type(obj).__qualname__) # Output: "Outer.Inner"
print(f"{type(obj).__module__}.{type(obj).__qualname__}")
# Output: "__main__.Outer.Inner"
Key Details & Edge Cases
- Why
type(obj).__name__is slightly preferred overobj.__class__.__name__:- For all normal new-style classes in Python 3,
type(obj)andobj.__class__point to the exact same class object. - However, custom proxy objects (like
unittest.mock.MagicMock,weakref.proxy, or SQLAlchemy lazy proxies) sometimes override the__class__descriptor to impersonate a wrapped target class, whereastype(obj)always returns the true underlying runtime type (and avoids triggering custom__getattr__hooks on proxy objects).
- For all normal new-style classes in Python 3,
- Avoid calling
str(type(obj))to extract a class name:str(type(items))returns"<class 'list'>"rather than"list". Always read the.__name__attribute directly instead of slicing or parsingstr(type(obj)).
- Nested classes (
__name__vs.__qualname__):- For a class defined inside another class or function,
type(obj).__name__returns only the innermost class name ("Inner"), whereastype(obj).__qualname__includes the enclosing scope path ("Outer.Inner"or"factory.<locals>.Inner").
- For a class defined inside another class or function,
- Passing a class object itself instead of an instance (
type(MyClass).__name__returns"type"):- If
xis already a class (x = User) rather than an instance (x = User()),type(x).__name__returns"type"(the metaclass name)! If a function may receive either a class or an instance, inspectx.__name__ if isinstance(x, type) else type(x).__name__.
- If
- Use
isinstance()for logic, and__name__only for logging, debugging, or error messages:- Never branch application logic on string comparisons like
if type(obj).__name__ == "User":—that breaks inheritance and collides across modules that define classes with the same name. Useisinstance(obj, User)for control flow and reservetype(obj).__name__for human-readable diagnostics.
- Never branch application logic on string comparisons like
Comparison of Class Name & Type Metadata Attributes
| Expression | Example Output (Outer.Inner()) |
Includes Enclosing Class / Module? | Best Used When |
|---|---|---|---|
type(obj).__name__ |
"Inner" |
No (short class name only) | Logging, custom __repr__, and error messages (recommended default). |
obj.__class__.__name__ |
"Inner" |
No (short class name only) | Identical to type(obj).__name__ for standard objects; respects proxy __class__ overrides. |
type(obj).__qualname__ |
"Outer.Inner" |
Enclosing classes/functions | Debugging nested classes or dynamically generated factory classes. |
type(obj).__module__ |
"__main__" / "pandas.core.frame" |
Module path only | Identifying which package/library defined an object’s class. |
f"{cls.__module__}.{cls.__qualname__}" |
"__main__.Outer.Inner" |
Yes (full dotted import path) | Serialization metadata, plugin registries, or disambiguating identically named classes. |
You must log in or register to comment.
