Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyCharm warning about 'not callable'

Tags:

python

pycharm

I write a rule engine with a parameter 'matcher', which could be a string, an Regular expression, or an function.

When I test and use this matcher:

    if hasattr(self.matcher, '__call__'):  # 函数
        match_this_rule = self.matcher(input_msg)

PyCharm give me an warning on the second line, saying 'matcher is not callable'.

How could i avoid PyCharm showing this?

like image 669
YeRuizhi Avatar asked Jul 23 '14 05:07

YeRuizhi


1 Answers

PyCharm cannot know, in general, whether your self.matcher will be callable. As far as PyCharm is converned you are only testing if the object has an attribute, but I doubt that PyCharm will recognize that the attribute name is constant and that the condition implies that the object is callable.

The only solution to change PyCharm behaviour is to disable the inspection for that statement

if hasattr(self.matcher, '__call__'):
    # noinspection PyCallingNonCallable
    match_this_rule = self.matcher(input_msg)

Instead of your home-made test, you could use the callable built-in function:

if callable(self.matcher):
    match_this_rule = self.matcher(input_msg)

In fact with PyCharm3.4 the above code doesn't trigger the warning because PyCharm recognizes the built-in callable function.


This said, it would be even better if you avoided to use three different types for your matcher. You can always wrap the non-function matchers into a function, or create a small class to perform the matches in a uniform way. This would also simplify the code, since you wouldn't need to continuously test for the type in order to use self.matcher.

like image 109
Bakuriu Avatar answered Oct 24 '22 14:10

Bakuriu