If I have a string which is the same as a python data type and I would like to check if another variable is that type how would I do it? Example below.
dtype = 'str'
x = 'hello'
bool = type(x) == dtype
The above obviously returns False but I'd like to check that type('hello') is a string.
-
What counts as "a Python data type"? Do you care about user-defined classes, for example?Karl Knechtel– Karl Knechtel2021年08月23日 23:50:25 +00:00Commented Aug 23, 2021 at 23:50
-
2If you have a set number of types, why not just create an explicit mapping?Karl Knechtel– Karl Knechtel2021年08月23日 23:51:08 +00:00Commented Aug 23, 2021 at 23:51
5 Answers 5
You can use eval:
bool = type(x) is eval(dtype)
but beware, eval will execute any python code, so if you're taking dtype as user input, they can execute their own code in this line.
Comments
Don't write :
bool = type(x) == dtype
because dtype is a variabe It is in the form of a string , not logical !!
you should be entered a statement to check is str or no
Also, the string in Python is an object so to call it write :
str not write dtype = 'str',exemple :
type(x) == str
i fixed your code and just try this :
x = 'hello'
if type(x) == str:
print(True)
else:
print(False)
It's a simple code but there are other shortcuts that come from Python
try that and good day for coding !!
Comments
If your code actually looks like the example you showed and dtype isn't coming from user input, then also keep in mind that str (as a value in Python) is a valid object which represents the string type. Consider
dtype = str
x = 'hello'
print(isinstance(x, dtype))
str is a value like any other and can be assigned to variables. No eval magic required.
1 Comment
I think the best way to do this verification is to use isinstance, like:
isinstance(x, str) # returns True
From the docs:
isinstance(object, classinfo)
Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns False. If classinfo is a tuple of type objects (or recursively, other such tuples), return True if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.
Comments
One solution is using .__name__ as follows:
dtype = 'str'
x = 'hello'
bool = type(x).__name__ == dtype