I've got the same warning on my project. I'm changing the source code to be py2/3 compatible, and pylint helps a lot.
Running pylint --py3k
shows only errors about compatibility.
In python 2, if use filter
, it returns a list
:
>>> my_list = filter(lambda x: x == 1, [1, 1, 2])
>>> my_list
[1, 1]
>>> type(my_list)
<type 'list'>
But in python 3, filter
and other similar methods (map
, range
, zip
, ..) return a iterator, that is incompatible types and perhaps cause bugs in your code.
>>> my_list = filter(lambda x: x == 1, [1, 1, 2])
>>> my_list
<filter object at 0x10853ac50>
>>> type(my_list)
<class 'filter'>
To make your code python 2/3 compatible, I use a cheat sheet from python future site
To avoid this warning, you can use 4 approaches, that works on python 2 and 3:
1 - Using a list comprehension like you said.
2 - Using a list
function, grant that return always is a materialized list, result is same on both python versions
>>> list(filter(lambda x: x == 1, [1, 1, 2]))
[1, 1]
3 - Using lfilter
, that's a future package import. It always return a list, uses filter on py2, and list(filter(..)
on py3. So, both pythons got the same behaviour and you got a cleaner syntax.
>>> from future.utils import lfilter
>>> lfilter(lambda x: x == 1, [1, 1, 2])
[1, 1]
4 - The best! Use filter
always on a loop, this way pylint don't give warnings, and it have a nice performance boost on python 3.
>>> for number in filter(lambda x: x == 1, [1, 1, 2]):
>>> print(number)
>>> 1
>>> 1
Always prefer functions that works on python 3, because python 2 will be retired soon.