1

I have a Python class with class attributes, and I would like it to show the values of the attributes when printed.

But instead, it just shows the name of the class.

class CONFIG:
    ONE = 1
    TWO = 2


print(CONFIG)  # <class '__main__.CONFIG'>

Of course, if I wanted to instantiate the class, then I could def __repr__() and control how it prints.

The question is, how do I control how a class (NOT a class instance) prints? Is there an equivalent to __repr__ for the class itself?

Workarounds:

  • Write a function that uses vars() or dir() to iterate over the attributes
  • Instantiate the class, stop doing things a weird way :)
  • Change my code in some other way so I no longer have the requirement to print the class (use Enum, SimpleNamespace, etc.)
David Gilbertson
  • 4,219
  • 1
  • 26
  • 32
  • In Python, everything is an object, including classes. If you want to control the behavior of a class object, you need to implement a *metaclass*, a class of a class. The base metaclass is `type`. All classes are instances of `type`, e.g. `isinstance(int, type)` – juanpa.arrivillaga Dec 18 '22 at 22:17
  • So implement your metaclass, `class MyMeta(type): ...`, e.g. `def __repr__(self): return "Example"` Then specify that your class definition statement that it should use the custom metaclass, `class MyClass(metaclass=MyMeta): ...` then `print(MyClass)` should give you `Example` – juanpa.arrivillaga Dec 18 '22 at 22:21
  • 1
    [Here is the basic documentation of how this all works](https://docs.python.org/3/reference/datamodel.html#metaclasses). – juanpa.arrivillaga Dec 18 '22 at 22:24

0 Answers0