Pylint across Python versions

Chris Angelico rosuav at gmail.com
Mon Feb 10 08:59:36 EST 2014


On Mon, Feb 10, 2014 at 10:39 PM,  <thomas.lehmann at adtech.com> wrote:
> Example:
> I'm using a construct like this:
>
> if sys.version.startswith("3."):
>     unicode = str
>
> The reason is that Python 3 does not have this
> function anymore but pylint yells for Python < 3
> about redefinition also it does not happen.
>
> How to get forward with this?

It's more common to spell that with a try/except. Does pylint complain
if you use this instead?

try:
    unicode
except NameError:
    unicode = str

Although it would be better to write your code for Python 3, and have
compatibility code at the top for Python 2. That would mean using
'str' everywhere, and then having this at the top:

try:
    str = unicode
except NameError:
    pass

That way, when you're ready to drop support for Python 2, you simply
delete the compat code and everything works. Otherwise, you have to
maintain messy code indefinitely.

Alternatively, to avoid redefinition at all, you could use your own
name everywhere:

try:
    unicode_string = unicode
except NameError:
    unicode_string = str

Use something less unwieldy if you prefer, but this avoids any chance
of collision :)

ChrisA



More information about the Python-list mailing list