Reputation: 4334
I have a python function that looks roughly like this:
def f(x):
[...]
g(x)
Sometimes, for reasons beyond my control x
is of type <bound method A.b of <A: a>>
. g()
is in a 3rd party library and can not handle this argument and throws an exception. So what I want to do before g()
is called is to test for this case and do something else instead:
def f(x):
[...]
if x == A.b:
doSometingElse()
else:
g(x)
Now, ==
does not seem to work as it is never true. What is the correct way to test if my variable x
contains the method A.b
?
Upvotes: 0
Views: 95
Reputation: 376052
The function in the class is turned into a bound method when accessed on an object, or an unbound method when accessed on the class. In Python 2, both types have a func attribute that refer to the function. So your test could look like:
if x.__func__ is A.b.__func__:
In Python 3 it's a little easier:
if x.__func__ is A.b:
Upvotes: 2
Reputation: 44
Maybe try to throw a try except in there
def f(x):
[...]
try:
g(x)
except:
do something else
this would be the easiest way to handle it.
Upvotes: -1