A new 2to3 fixer for unicode dundermethods19 Mar 2021
In Python 2 Django prefers using the
__unicode__ member of any class to get human-readable strings to its interfaces. In Python 3 however, it defaults to the
__str__ member. Porting guides and utilities specific to Django used to solve this by suggesting having a
__str__ method, with the
python_2_unicode_compatible decorator on the class.
This was a nice enough solution for a long time, for code bases migrating from Python 2 to Python 3 or wanting to support both at the same time.
However, with the official deprecation of Python 2 on January 1st 2020, adding this decorator started making less sense to me.
Now you definitely only should support Python 3 runtimes for Django projects.
As an additional porting utility, I created a fixer for
2to3, that renames all
__unicode__ dundermethods to
__str__, where possible.
The current status of the fixer util is that I have created a pull request on the
2to3 library (even though I’m not sure whether it will be accepted).
lib2to3 is no longer maintained, so just get the fixer from the diff of the closed pull request if you want to use it.