7

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?

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for turning matcher into a consistent type as early as possible
This answer is good the the pyCharm comment, however I think this stackoverflow.com/a/58170133/13903942 is better since is not IDE depented (and is not a comment but actually typing code)
2

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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.