Reputation: 973
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?
Upvotes: 7
Views: 9523
Reputation: 59
Use typing so PyCharm will understand what kind of object is being used.
something like:
class TestClass:
matcher: Type[ClassObject] = ClassInstance
or
if hasattr(self.matcher: Type[ClassObject], '__call__'): # 函数
match_this_rule = self.matcher(input_msg)
Upvotes: 2
Reputation: 102039
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
.
Upvotes: 11