Consider this:
a = "True"
b = bool
How can I convert "a" into a a boolean?
In essence what I am looking for is something like:
a = "True"
b = bool
c = str_to_type(a, b)
print(c)
--> True
a = "1"
b = int
c = str_to_type(a,b)
print(c)
--> 1
And in the event "a" is not compatible with the class specified in "b" then I expect str_to_type to return None.
I'm trying to avoid having to write a if-else block, but if there isn't an elegant way to do this, I'll consider if-else. After all, I'm only looking at a few simple data types: int, float, str, bool. I am not looking to support user-defined classes.
I currently have this implemented:
def str_to_type(value: str, data_type: object):
if (data_type is bool):
if value.lower() in ("true"):
return True
elif value.lower() in ("false"):
return False
else:
return None
elif (data_type is int):
try:
return int(value)
except:
return None
elif (data_type is float):
try:
return float(value)
except:
return None
elif (data_type is str):
return value
else:
return None
CodePudding user response:
I guess you can simply do:
def str_to_type(a, b):
return b(a)
x = str_to_type('True', bool)
print(type(x), x) # <class 'bool'> True
x = str_to_type('1', int)
print(type(x), x) # <class 'int'> 1
CodePudding user response:
eval is what you might be looking for:
>>> a = "True"
>>> b = bool
>>> b(eval(a))
True
>>> a = "1"
>>> b = int
>>> b(eval(a))
1
Disclaimer:
Most of the time, eval
is not the correct solution for your problem. If you tell what is your end goal with this strategy, we might suggest a better approach.