See my answer below; after posting the question I realized what was going on.
My attempt to override the string representation of a class using a decorator isn't working. I must be missing something but can't figure out what it is.
from functools import wraps
def str_dec(obj):
@wraps(obj.__str__)
def __str__(cls):
return '<desired result>'
obj.__str__ = __str__
return obj
@str_dec
class Test():
pass
assert Test.__str__(Test) == '<desired result>' # success
assert str(Test) == '<desired result>' # failure
Obviously the new Test.__str__
method is being created successfully, but I was expecting it to be called by the str
function. Instead, str
is using the default string creation method (for type
objects).
I can get str
working using a metaclass, but then the __str__
method doesn't work! And I would prefer to use a decorator anyway.
class str_meta(type):
def __str__(cls):
return '<desired result>'
class Test(metaclass = str_meta):
pass
assert str(Test) == '<desired result>' # success
assert Test.__str__(Test) == '<desired result>' # failure
What is going on here? How can I override __str__
consistently for my class?