I have a (bad?) habit of displaying classes in Python like structures in Matlab, where each attribute is printed along with its value in a nice clean layout. This is done by implementing the __repr__
method in the class.
When working with objects inside of dictionaries or lists, this display style can be a bit distracting. In this case I'd like to do a more basic display.
Here's the envisioned pseudocode:
def __repr__(self):
if direct_call():
return do_complicated_printing(self)
else:
#something simple that isn't a ton of lines/characters
return type(self)
In this code direct_call()
means that this isn't being called as part of another display call. Perhaps this might entail looking for repr
in the stack? How would I implement direct call detection?
So I might have something like:
>>> data
<class my_class> with properties:
a: 1
cheese: 2
test: 'no testing'
But in a list I'd want a display like:
>>> data2 = [data, data, data, data]
>>> data2
[<class 'my_class'>,<class 'my_class',<class 'my_class'>,<class 'my_class'>]
I know it is possible for me to force this type of display by calling some function that does this, but I want my_class
to be able to control this behavior, without extra work from the user in asking for it.
In other words, this is not a solution:
>>> print_like_I_want(data2)