__str__ and __unicode__methods

Asked

Viewed 842 times

3

I’ve seen class codes that implement Django models overwriting both the method __str__ like the __unicode__, there is difference between them? If yes, there is some case that I should prefer one over another?

  • Are you using Python 2 or 3? I got problems with Python version with this; when I was studying Django, I did a project and I went through this doubt; I believe that at some point I committed something explaining this change

  • It seems that it was in that commit that I made that change

  • I’m using Python 3.

  • 1

    If you are using Python 3 you don’t even need the method __unicode__(never) or calls to encode that I happen to find inside ancient codes of the __str__.

  • Thanks @jsbueno.

1 answer

5


there’s a difference between them?

__str__() is an older form (returns bytes). __unicode__() is a new shape (returns characters, usually in UTF-8).

In Django, it’s good practice to do __str__() also return Unicode if you use Python 2:

def __str__(self):
    return unicode(self).encode('utf-8')

For the documentation, __unicode__() is called first. If there is no, __str__() is called.

If so, is there any case I should prefer one over another?

For Python 2, where Unicode is not guaranteed transparently, __unicode__() is preferable to be used.

For Python 3, __str__() is already naturally Unicode, so there is no need to have both.

  • I think what you said about returning bytes is valid for Python2; I understood something else by reading the documentation on Python3

  • In fact, I was more confused when reading the documentation in Python2...

  • 1

    On the link you mentioned says "In Python 3, there’s Simply str(), which must Return str (text)", after reading this statement in the documentation, I was confused by the part you say that str() is an older and Unicode() is a newer form...

  • Moral of the story? In Python3 ignore the __unicode__?

  • I think you’re making this very difficult. Python 3 works with Unicode more transparently, while in Python 2 the string is a byte representation, not necessarily in Unicode. I can add that to the answer if you like.

  • @Gypsy rhyming would be great, please

  • 1

    @Gypsy omorrisonmendez, thank you very much

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.