I tried the globals() method suggested by @Abdul, but that did not work in some cases, so I modified it slightly. This provides the extra feature of being able to use type coersion.
isinstance(x,getattr(globals()['__builtin__'],type_as_string))
The benefit is that we can also use this to generate an instance of an arbitrary type, and avoid Python trying to decide what type that is at assignment time.
cls = getattr(globals()['__builtin__'],type_as_string)
inst = cls(value_to_create)
Update (simplified, ~ Python3.11+ ??), i.e. on more recent Python.
cls = getattr(__builtins__,type_as_string)
e.g. (updated)
cls1 = getattr(__builtins__,'str')
cls2 = getattr(__builtins__,'float')
cls3 = getattr(__builtins__,'complex')
cls4 = getattr(__builtins__,'int')
inst1 = cls1(1)
inst2 = cls2(1)
inst3 = cls3(1)
inst4 = cls4(1)
print(type(cls1), f"'{inst1}'", type(inst1))
print(type(cls2), f"'{inst2}'", type(inst2))
print(type(cls3), f"'{inst3}'", type(inst3))
print(type(cls4), f"'{inst4}'", type(inst4))
print('str', isinstance(inst1, str))
print('float', isinstance(inst2, float))
print('complex', isinstance(inst3, complex))
print('int', isinstance(inst4, int))
for inst in (inst1, inst2, inst3, inst4):
print(inst,
"is complex? =",
isinstance(inst,getattr(__builtins__,"complex")))
Output:
<class 'type'> '1' <class 'str'>
<class 'type'> '1.0' <class 'float'>
<class 'type'> '(1+0j)' <class 'complex'>
<class 'type'> '1' <class 'int'>
str True
float True
complex True
int True
1 is complex? = False
1.0 is complex? = False
(1+0j) is complex? = True
1 is complex? = False