PyCQA / modernize

Modernizes Python code for eventual Python 3 migration. Built on top of fissix (a fork of lib2to3)
https://modernize.readthedocs.org/
Other
355 stars 51 forks source link

Need fixer for list.sort(cmp=...) #116

Open techtonik opened 9 years ago

techtonik commented 9 years ago

Unhandled Python 2 code:

    available_logs.sort(cmp=lambda x1, x2: locale.strcoll(x1['path'], x2['path']))
TypeError: 'cmp' is an invalid keyword argument for this function
daira commented 9 years ago

I don't see a straightforward, idiomatic way to replace cmp= with key=. https://wiki.python.org/moin/HowTo/Sorting#The_Old_Way_Using_the_cmp_Parameter gives a way to do so using an auxiliary class, but:

takluyver commented 9 years ago

The cmp_to_key wrapper is actually in functools, so we could write a fixer using that.

I agree that in most cases there will be a simpler and probably more efficient key function than using cmp_to_key(). Where the cmp function is supplied as a lambda, you could try to match a pattern like lambda x, y: cmp(x.age, y.age) and translate it to key=lambda x: x.age - but I think that would be a lot of effort for relatively little reward.

daira commented 9 years ago

functools.cmp_to_key is only in Python 2.7, and we claim to support Python 2.6. We could make it an opt-in fixer I suppose.

techtonik commented 9 years ago

I think that at least getting warning during processing is a must have. Otherwise the error will popup at run-time when line will be triggered.

It may worth to maintain a sane cookbook with explanations why particular problem exists, and how it can be manually adjusted.

techtonik commented 9 years ago

Like Debian linter does - https://lintian.debian.org/tags/out-of-date-standards-version.html

takluyver commented 9 years ago

Python-modernize doesn't generally do warnings, and it certainly doesn't guarantee that the code will run unmodified on python 3 afterwards. I know Brett Cannon was working on putting some python 3 compatibility checks into pylint to complement the fixes in python-modernize.

daira commented 9 years ago

The cookbook would be http://python3porting.com/ -- I believe @brettcannon had plans to update it to recommend python-modernize.