[Python-ideas] sys.py3k

Chris Angelico rosuav at gmail.com
Thu Nov 8 00:14:35 CET 2012


On Thu, Nov 8, 2012 at 5:35 AM, anatoly techtonik <techtonik at gmail.com> wrote:
> I thought of sys.py3k check as an explicit way to guard the code that should
> be maintained extra carefully for Python 3 compatibility, so that you can
> grep the source for this constant and remove all the hacks (such as bytes to
> string conversion) required to maintain the compatibility when the time
> comes to switch.

I agree about greppability, it's a huge help. Hence the code comment;
as long as you're consistent and you pick a keyword long enough or
unusual enough to not occur anywhere else, you can easily do a "find
across files" or "grep XYZ *" to find them all. And if you put the
comment on the most significant line of code, line-based tools will be
more useful.

# Unideal:
# py3k
try:
    reload
except NameError:
    from imp import reload

# Better:
try: # py3k
    reload
except NameError:
    from imp import reload

# Best:
try:
    reload # py3k
except NameError:
    from imp import reload

# Also best:
try:
    reload
except NameError:
    from imp import reload # py3k

Taking just the line with the keyword "py3k" on it will tell you
exactly what that file is doing.

ChrisA


More information about the Python-list mailing list