0

Is there a way to change how my class is printed using print instead of the standard <class [name]>? Wasn't able to find an attribute that I can override.

Reason I am asking: I have long chain of modules so it gets hard to debug when the class name is printed as <class a.b.c.d.e.Foo>. I'd like to print just Foo if possible.

JRR
  • 6,014
  • 6
  • 39
  • 59
  • @KellyBundy `print(Foo)` where `Foo` is a class that I defined myself. – JRR Jun 26 '23 at 04:53
  • @KellyBundy I know how to get the name of the class. I am asking how to change the way the class's name is printed. – JRR Jun 26 '23 at 05:02
  • As an addition to the other question that already mostly answers yours (https://stackoverflow.com/questions/4932438/): If you want to have a *reusable* metaclass that does not "hard-code" the printout but prints the class name as you prefer, write the metaclass's `__str__` or `__repr__` function as follows: `def __repr__(self): return self.__name__`. Because in the metaclass, `self` refers to your class (`Foo` in your case), and not to its instances. This is because classes are instances of their metaclass (let that sink in). – simon Jun 26 '23 at 15:51

1 Answers1

0

Override __repr__.

>>> class Foo: pass
...
>>> print(Foo())
<__main__.Foo object at 0x7f7296192da0>
>>> class Foo:
...   def __repr__(self):
...     return "Foo"
...
>>> print(Foo())
Foo

Note that converting to an object to a string will call __str__ first and then fall back to __repr__

>>> class Foo:
...   def __repr__(self):
...     return "Foo"
...   def __str__(self):
...     return "Foo (string)"
...
>>> f"{Foo()}"
'Foo (string)'
>>> str(Foo())
'Foo (string)'
>>> Foo()
Foo

You may also wish to read How can I choose a custom string representation for a class itself (not instances of the class)? for information on changing the representation of a class as opposed to instances of that class.

Chris
  • 26,361
  • 5
  • 21
  • 42
  • I'm asking how to change the way the name of a _class_ is printed, not how an instance is printed. In your example it's the same as trying to change what gets printed out when you call `print(Foo)` – JRR Jun 26 '23 at 04:43