[Dev] Re: Those annoying __str__ methods
Andi Vajda
vajda at osafoundation.org
Tue Jan 18 13:44:14 PST 2005
> You mentioned how often you curse those __str__ methods, on items like
> EmailAddress, and I've been thinking maybe we should move them. You hate is
> that they are hooked in to str(), so you end up calling them by accident,
> often when debugging as I recall. What I like is that there's a known way to
> convert things to a nice user-readable representation. The Chandler
> convention of using the "displayName" attribute doesn't seem to work well in
> some cases, because you may need a method to decide how to display. You
> probably want a method for ref collections, and even things like EmailAddress
> have a couple different ways that they display based on whether or not a
> fullName attribute is present. So I figured __str__ was the standard way to
> do this when a method is needed. But there's no reason we need to use
> __str__. Maybe we should use a display() method instead of __str__, and both
> of us will be happy?
>
> We don't actually have very many __str__ methods yet, so it wouldn't be too
> hard to make a change like this. It would be great if ref collections knew
> how to display themselves as a nice comma-separated list of displayed items.
> Most items would inherit a default display() method that just uses the
> displayName attribute.
>
> What do you think? Should we move the __str__ methods? Is there some other
> standard that we should be adopting? Let me know if you think this is a good
> idea, and I'll try to work with you on this.
__str__() gets called by python automagically when it thinks it needs a string
representation of an object. On Item, I defined __repr__(), its sister method,
which gets called by __str__() when no __str__() method is defined.
The problem with using __str__() for debugging is that there is only one
__str__() but there are many different debugging needs. I really need to see
the actual item, not just a string saying 'me', for example.
Because this has been a problem for a while and there is no good solution, I
just started using Item._repr_() which forces a call to Item.__repr__()
whenever I need an actual repository-debugging-formatted item string.
So, from my perspective, the problem is solved already, I just use _repr_().
As for a string representation of a ref collection, that is somewhat iffy as
these can be huge and a really loooooooooong string would then be generated.
Some ... logic would be necessary in there.
I use RefList.dir() for debugging, this method prints one line per item
reference.
Still, maybe I should add an Item.getItemDisplayString() method that defaults
to the existing Item.getItemDisplayName() method for a more user-friendly way
to produce user-readable strings from items ?
Andi..
More information about the Dev
mailing list