I've run into certain code snippet which recreates some objects every time in the __str__ method of a class.
From what I recall, the __str__ method shouldn't bother with object creation. It should just do simple formatting operations and return a string.
But I do not have any evidence for such statement. Is there any convention or perhaps a PEP explaining proper __str__ usage? I've found only PEPs regarding str vs. repr usage.
I've searched Stack Overflow, but I haven't found an answer.
Edit:
You've asked for example. Unfortunately I can't share the snippet, because it isn't mine. I'm asking for general guidelines by the community (if such thing exists).
Here's a roughly similar usage:
from collections import OrderedDict
class A:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __str__(self):
# recreated every time...
dict_sorted = OrderedDict(sorted(self.__dict__.items()))
result = []
for i in dict_sorted.keys():
result.append(str((i, dict_sorted[i])))
return ' '.join(result)
if __name__ == "__main__":
a = A('foo', 'bar', 'baz')
print(a)