Explain Codes LogoExplain Codes Logo

Getting the class name of an instance

python
class-name
type-method
instance
Alex KataevbyAlex Kataev·Aug 9, 2024
TLDR

To get the class name of an instance in Python, apply the instance.__class__.__name__ formula:

class_name = instance.__class__.__name__

This provides the class name as a string for any instance, referred to as 'instance'.

Class name retrieval 101

Here's your toolkit for getting the class name of an instance in Python. Keep these snippets up your sleeve:

type() method: New kid on the block

With new-style classes (most commonly used in Python 3 and Python 2.2+), grab the class name with type(instance).__name__:

# Hey look, it's a wild cat! cat = Cat() # Thundercats, ho! class_name = type(cat).__name__ # Yields "Cat"

New-style classes come to life by inheriting from object. Remember, sharing is caring:

class Cat(object): # Inherits love from 'object' pass

instance.class.name: Oldie but goldie

The instance.__class__.__name__ expression works like a charm with old-style classes and is universally compatible:

class Dog: # Classic (old-style) dog doesn't know new tricks in Python 2 pass # Meet Rufus, the classic dog. rufus = Dog() # Rufus reveals his true identity! class_name = rufus.__class__.__name__ # Barks out "Dog"

Self-aware classes: Gazing at the mirror

Inside a class method, use type(self).__name__ to get the class name. It's like asking, "Mirror, mirror on the wall, what's my class name after all?"

class Bird(object): def bird_talk(self): # Birds now know their names, what a time to live! return type(self).__name__

Full package identification: Full steam ahead

In cases where classes of the same name exist across different modules, bring out the heavy artillery with the module name and the class name together:

# A moment of full disclosure full_class_name = "{0}.{1}".format(instance.__class__.__module__, instance.__class__.__name__)

type() vs class: Choose wisely

The line between type() and __class__ might blur at times. Old-style vs New-style classes are notorious for their subtleties, so get acquainted with them in the Python Wiki.

Inspect-free zone: Keeping it simple

Keeping things simple is key, therefore almost always, creating an __inspect__ module to fiddle with class names is overkill. Stick to type() and __name__ for a more simple way out.

Sailing through pitfalls

While solutions abound, just like any journey, you might encounter bumps on the road. Here's what to watch out for:

Unusual suspects: Not all follow the rules

Behold! Some instances might override class retrieval methods:

class CustomMeta(type): def __str__(cls): # "I'm a special unicorn...no not really!" return "Special" class CustomClass(metaclass=CustomMeta): pass # Warning: Might not spit out 'CustomClass' as expected! print(str(CustomClass))