How do you get the class name of an object instance in Python? | A1Lab@MZeeshanM to PythonEnglish • 4 days ago

How do you get the class name of an object instance in Python?

message-square
0

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 over obj.__class__.__name__:
    • For all normal new-style classes in Python 3, type(obj) and obj.__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, whereas type(obj) always returns the true underlying runtime type (and avoids triggering custom __getattr__ hooks on proxy objects).
  • 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 parsing str(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"), whereas type(obj).__qualname__ includes the enclosing scope path ("Outer.Inner" or "factory.<locals>.Inner").
  • Passing a class object itself instead of an instance (type(MyClass).__name__ returns "type"):
    • If x is 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, inspect x.__name__ if isinstance(x, type) else type(x).__name__.
  • 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. Use isinstance(obj, User) for control flow and reserve type(obj).__name__ for human-readable diagnostics.

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.