Get fully qualified class name of an object in Python

Learn get fully qualified class name of an object in python with practical examples, diagrams, and best practices. Covers python, python-datamodel development techniques with visual explanations.

How to Get the Fully Qualified Class Name of an Object in Python

Hero image for Get fully qualified class name of an object in Python

Learn various methods to retrieve the complete, unambiguous class name of any Python object, including its module path, for debugging, logging, and dynamic operations.

In Python, understanding an object's type and origin is crucial for many programming tasks, from debugging and logging to serialization and dynamic introspection. The 'fully qualified class name' provides a precise identifier, including the module where the class is defined, which is more informative than just the class name itself. This article explores several robust methods to obtain this information, detailing their usage and underlying principles.

Understanding Fully Qualified Names

A fully qualified class name typically follows the format module_name.ClassName. For example, a datetime object from the datetime module would have a fully qualified name like datetime.datetime. This convention helps avoid naming collisions and provides a clear path to import or reference the class dynamically. Python's introspection capabilities make it straightforward to extract this information from any object.

flowchart TD
    A[Start with an Object] --> B{Get Object's Class}; 
    B --> C{Get Class's Module Name}; 
    B --> D{Get Class's Name}; 
    C --> E[Combine Module and Class Name];
    D --> E;
    E --> F[Fully Qualified Name];

Flowchart illustrating the process of obtaining a fully qualified class name.

Method 1: Using __module__ and __qualname__

The most common and recommended way to get the fully qualified class name is by combining the __module__ and __qualname__ (or __name__) attributes of an object's class. The __module__ attribute returns the name of the module in which the class was defined, while __qualname__ provides the qualified name of the class within its module, which includes any enclosing class names for nested classes. For top-level classes, __qualname__ is usually the same as __name__.

import datetime

class MyClass:
    pass

class Outer:
    class Inner:
        pass

def get_fully_qualified_name(obj):
    cls = obj.__class__
    module = cls.__module__
    qualname = cls.__qualname__
    if module == 'builtins': # For built-in types like int, str
        return qualname
    return f"{module}.{qualname}"

# Examples
print(get_fully_qualified_name(datetime.datetime.now()))
print(get_fully_qualified_name(MyClass()))
print(get_fully_qualified_name(Outer.Inner()))
print(get_fully_qualified_name(123))
print(get_fully_qualified_name("hello"))

Using __module__ and __qualname__ to get the fully qualified class name.

Method 2: Using type() and __name__ (Simpler for non-nested classes)

For simpler cases, especially with top-level classes and when __qualname__ is not strictly necessary (i.e., no nested classes), you can use type(obj).__module__ and type(obj).__name__. This approach is slightly less robust for nested classes but perfectly adequate for most common scenarios.

import os

class AnotherClass:
    pass

def get_simple_qualified_name(obj):
    cls = type(obj)
    module = cls.__module__
    name = cls.__name__
    if module == 'builtins':
        return name
    return f"{module}.{name}"

# Examples
print(get_simple_qualified_name(os.path))
print(get_simple_qualified_name(AnotherClass()))
print(get_simple_qualified_name([]))

# Demonstrating difference with nested classes (if __qualname__ was not used)
class Outer:
    class Inner:
        pass

# This will output 'Outer.Inner' if using __qualname__, but 'Inner' if only using __name__
# The get_simple_qualified_name function above would return 'your_module_name.Inner' for Outer.Inner()
# if Outer and Inner were defined in 'your_module_name.py'
print(f"Nested class with __name__: {get_simple_qualified_name(Outer.Inner())}")

Using type() and __name__ for a simpler qualified name.

Practical Applications

Knowing an object's fully qualified class name is invaluable in several scenarios:

  • Logging and Debugging: Clearly identify the type of object causing an issue or being processed.
  • Serialization/Deserialization: When saving and loading objects, the fully qualified name can be used to dynamically import the correct class for reconstruction.
  • Dynamic Class Loading: Programmatically import and instantiate classes based on their string names.
  • Configuration: Storing class references in configuration files as strings.
  • Metaprogramming: Advanced scenarios where code needs to inspect and manipulate types at runtime.

By leveraging Python's powerful introspection features, you can reliably obtain the fully qualified class name of any object, enhancing the robustness and flexibility of your applications.