Opened 11 years ago

Closed 10 years ago

#6833 closed (wontfix)

Leaving the u off a string returned from __unicode__ results in horribly hard to debug bugs

Reported by: Simon Willison Owned by: nobody
Component: contrib.admin Version: master
Severity: Keywords:
Cc: Triage Stage: Design decision needed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Ramiro Morales)

I hit a nasty bug where weird unicode errors were being thrown in the admin application, which it turned out was caused because I was returning a bytestring from a __unicode__ method. It would be great if Django could spot this mistake and throw a more humanly readable exception. This might just involve a few assertions in the admin code.

Change History (3)

comment:1 Changed 10 years ago by Ramiro Morales

Description: modified (diff)

comment:2 Changed 10 years ago by Jeff Anderson

Triage Stage: UnreviewedDesign decision needed

comment:3 Changed 10 years ago by Malcolm Tredinnick

Resolution: wontfix
Status: newclosed

I think this is probably a bit optimistically hopeful, unfortunately. We're talking about the __unicode__ method; one of Python's base methods, essentially. Python itself forcibly converts the returned value from that method to have unicode type. So the only way to detect any problems would be to do something convoluted such as having Django's Model.__unicode__ actually call some other Model.not_really_unicode() method and it's that latter method that you implement. That would look really unnatural (even when we choose a less stupid name for the wrapped method), given then number of __unicode__ methods one writes in the course of events.

I think Django code should still always look like Python. You could write your own __unicode__ wrapper as above in a subclass of Model and always inherit from MyModelSubclass, I guess. But I wouldn't want to put that into Django itself, since it's punishing (readability and performance-wise) everybody else's code.

I agree that errors like this are sometimes hard to debug because of the forced type coercion and it would have been better if __unicode__ raised an exception at that point. But that's the way Python is written.

So although I seem to be wontfixing a bunch of your bugs today, Simon (and I'm really not picking on you; it's just the ticket contents, not the reporter. Honest!), I think this is one of those things we can't do much about but where you could program defensively as indicated above if you were willing to write not-quite-Python and pay the readability trade-off.

Note: See TracTickets for help on using tickets.
Back to Top