There is a Class from a third party lib I am using.
def funcA(base):
class ClassA(base):
def __init__(self, obj):
....
I have an instance of ClassA a
type(a)
# prints <class 'path.to.module.funcA.<locals>.ClassA'>
How can I check if a variable is an instance of ClassA? I am not sure how to reference ClassA since it is under a function....
import module
isinstance(a, module.funcA.ClassA?) <--- how to reference ClassA?
If you are not able to change funcA
itself because it's not in your own code, then a neat way to test for instances is to give it a superclass and test for the superclass. Replace funcA
with a wrapped version, which calls the original funcA
with a class that extends both base
and your own ClassABase
:
import functools
class ClassABase:
pass
def funcAwrapper(f):
@functools.wraps(f)
def wrapper(base):
class WrappedBase(base, ClassABase):
pass
return f(WrappedBase)
return wrapper
funcA = funcAwrapper(funcA)
Now all of the instances of ClassA
created by funcA
will also be instances of your own ClassABase
, so you can test isinstance(obj, ClassABase)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.