Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

Python "isinstance" with class name instead of type

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 wnat to use the class name, so isinstance(c_inst, A) is not available in this case.

question from:https://stackoverflow.com/questions/65858077/python-isinstance-with-class-name-instead-of-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
    class Unused:
        pass
    cls = cls or Unused
    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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...