Is there a way to simply my code below to not use a bunch of if-then-else?
if isinstance(t, int): v = 10
elif isinstance(t, bool): v = 20
elif isinstance(t, string): v = 30
...
Is there a way to simply my code below to not use a bunch of if-then-else?
if isinstance(t, int): v = 10
elif isinstance(t, bool): v = 20
elif isinstance(t, string): v = 30
...
You can use a dict
that maps your types to your values, like this:
TYPE_TO_VALUE = {
"int": 10,
"bool": 20,
"string": 30
}
and then assign your value like this v = TYPE_TO_VALUE[type(t).__name__]
I would go with list comprehension (this way you will cover the case for bool
).
map_={int: 10, bool: 20, str: 30}
type_map=lambda x: [map_.get(el) for el in map_.keys() if isinstance(x, el)]
t=4
print(type_map(t))
# [10]
t=True
print(type_map(t))
# [10, 20]
t="txt"
print(type_map(t))
# [30]
t=5.3
print(type_map(t))
# []
Alternatively to cut it down to the relevant part (IMO):
map_={bool: 20, int: 10, str: 30} # notice order change
type_map=lambda x: ([map_.get(el) for el in map_.keys() if isinstance(x, el)]+[None])[0]
t=4
print(type_map(t))
# 10
t=True
print(type_map(t))
# 20
t="txt"
print(type_map(t))
# 30
t=6.7
print(type_map(t))
# None
One approach may be to do arithmetic with the boolean isinstance
result.
def map_instance( t ):
return isinstance( t, int ) * 10 +
isinstance( t , bool ) * 10 + # bool returns 20 as it's int and bool.
isinstance( t, str ) * 30 )
I think this can handle subclassing.
two alternatives, I would choose first one (the function)
def get_v(my_object):
my_types = {bool:20, int:10, str:30}
for my_type, value in my_types.items():
if isinstance(my_object, my_type): # first seen wins
return value
class Spam(str):
pass
s = Spam()
v = get_v(s)
print(v)
# ugly alternative
my_types = {'bool':20, 'int':10, 'str':30}
print(my_types.get(s.__class__.__bases__[0].__name__)) # in multiple inheritance it will take first one
If the dict is order-preserving (e.g. 3.7+) and bool is before int, first seen wins