1

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.

2
  • What counts as "a Python data type"? Do you care about user-defined classes, for example? Commented Aug 23, 2021 at 23:50
  • 2
    If you have a set number of types, why not just create an explicit mapping? Commented Aug 23, 2021 at 23:51

5 Answers 5

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

0

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

dtype is being read in from a csv so I don't have control over the variable in that way
0

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. 

https://docs.python.org/3/library/functions.html#isinstance

Comments

0

One solution is using .__name__ as follows:

dtype = 'str' x = 'hello' bool = type(x).__name__ == dtype 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.