So I have a function (let's call it fun1) that accepts a function as a parameter. But inside fun1, I need to access the parameter's __self__, which exists only if the function is a bound method.
The function itself must accept two str args and return a bool.
In other words, like this:
MyFuncType = Callable[[str, str], bool] # fun1 is an unbound function def fun1(func: MyFuncType): ... o = func.__self__ ... # Some logic on the "o" object, such as logging the object's class, # doing some inspection, etc. ... If I use MyFuncType like the above, PyCharm will complain that __self__ is not an attribute of func.
So, what type hint should I annotate func with, so that PyCharm (and possibly mypy) won't protest on that line?
(I'm using Python 3.6 by the way)
Callable[[<class>, str, str], bool]? You would need to passClass.methodinstead ofself.method, does your scenario allow that? Then you would declareoto be the first argument of thatCallable.funcwas bound to and log that, plus doing some inspection on the object. So, passing a reference to an object to the func definitely won't help. Notice in the example thatfun1was a standalone function, it has noselfto pass tofunc.