Python "isinstance" with class name instead of type
Question:
I want to check if an object or variable is an instance of the specified class type, but using the name of this class, not its type. Something like this:
class A: pass
class B(A): pass
class C(B): pass
c_inst = C()
# Not working, isinstance expects the type:
ok = isinstance(c_inst, 'A')
Are there any alternatives? I want to use the class name, so isinstance(c_inst, A)
is not available in this case.
Answers:
If you only have the class name as a string, you could do this
>>> class Foo:pass
...
>>> foo = Foo()
>>> foo.__class__.__name__ == 'Foo'
True
>>> foo.__class__.__name__ == 'Bar'
False
However this isn’t very reliable, because Foo.__class__.__name__
is writeable
>>> foo.__class__.__name__ = 'Baz'
>>> foo.__class__.__name__ == 'Foo'
False
For superclasses, you could do something like
foo.__class__.__name__ == 'X' or 'X' in [c.__name__ for c in foo.__class__.__bases__]
though this won’t pick up object
.
Came up with this way, note: the class you are checking must be in globals though:
import inspect
def isinstance_string(variable, string):
cls = globals().get(string, None)
if inspect.isclass(cls):
return isinstance(variable, cls)
return False
class A: pass
class B(A): pass
class C(B): pass
c_inst = C()
ok = isinstance_string(c_inst, 'A')
I want to check if an object or variable is an instance of the specified class type, but using the name of this class, not its type. Something like this:
class A: pass
class B(A): pass
class C(B): pass
c_inst = C()
# Not working, isinstance expects the type:
ok = isinstance(c_inst, 'A')
Are there any alternatives? I want to use the class name, so isinstance(c_inst, A)
is not available in this case.
If you only have the class name as a string, you could do this
>>> class Foo:pass
...
>>> foo = Foo()
>>> foo.__class__.__name__ == 'Foo'
True
>>> foo.__class__.__name__ == 'Bar'
False
However this isn’t very reliable, because Foo.__class__.__name__
is writeable
>>> foo.__class__.__name__ = 'Baz'
>>> foo.__class__.__name__ == 'Foo'
False
For superclasses, you could do something like
foo.__class__.__name__ == 'X' or 'X' in [c.__name__ for c in foo.__class__.__bases__]
though this won’t pick up object
.
Came up with this way, note: the class you are checking must be in globals though:
import inspect
def isinstance_string(variable, string):
cls = globals().get(string, None)
if inspect.isclass(cls):
return isinstance(variable, cls)
return False
class A: pass
class B(A): pass
class C(B): pass
c_inst = C()
ok = isinstance_string(c_inst, 'A')