Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyLint W0143 warning: Comparing against a callable

Tags:

python

pylint

I trying to test pylint with default settings and (see python code below) get a warning:

>pylint pylint_test_01.py
>pylint_test_01.py:24:7: W0143: Comparing against a callable, did you omit the parenthesis? (comparison-with-callable)

How can I get rid of this pylint warning without breaking this algorithm and without disable pylint checks (i.e. with default settings)? General principle of enumerating functions from list should remain.

'''Test pylint with default settings warnings'''
from random import randint
def sortaray_builtin(arr):
    '''This is built in Python sort function'''
    return sorted(arr.copy())
def sortaray_bubble(arr):
    '''Bubble sorting algorithm -- is a simplest of sorting algorithms. Perfomance: O(N**2)'''
    brr = arr.copy()
    for i, _ in enumerate(brr[:-1]):
        for j in range(i, len(brr)):
            if brr[i] > brr[j]:
                brr[i], brr[j] = brr[j], brr[i]
    return brr

SFUNCTIONS = [
    sortaray_builtin,
    sortaray_bubble
]

ARSIZE = 20
ARRY = [randint(0, ARSIZE) for i in range(ARSIZE)]

for SrtFunc in SFUNCTIONS:
    # Line below cause an W0143: Comparing against a callable, did you omit the parenthesis? (comparison-with-callable)
    if SrtFunc == sortaray_builtin:
        print("Builtin: ", end='', flush=True)
    else:
        print("Bubble : ", end='', flush=True)
    print(SrtFunc(ARRY))
like image 483
An0ther0ne Avatar asked Sep 07 '25 00:09

An0ther0ne


2 Answers

You could use is for function comparisons:

if SrtFunc is sortaray_builtin:

This is also what happens under the hood when you use == to compare two functions, as there is no way to otherwise determine if two functions are equivalent.

Also see this question for more details on how comparisons on functions work.

like image 164
Zecong Hu Avatar answered Sep 09 '25 13:09

Zecong Hu


Option 1

You can disable checks for some places.

if SrtFunc == sortaray_builtin:  # pylint: disable=W0143

More info https://pylint.readthedocs.io/en/latest/user_guide/message-control.html

Option 2

You can get the name of a function with __name__ attribute.

SrtFunc.__name__ == builtin_sort.__name__

Option 3

Same as the second method, but with .__doc__

SrtFunc.__doc__ == builtin_sort.__doc__

Option 4

You can wrap your functions in objects, e.g. in dict, or create a special class.

class Sorter():
    def __init__(self, func):
        self.sort = func
builtin = Sorter(sortaray_builtin)
bubble = Sorter(sortaray_bubble)
SFUNCTIONS = [ builtin, bubble ]
builtin.sort()
like image 41
Maxim Krabov Avatar answered Sep 09 '25 15:09

Maxim Krabov