try..except or type() or isinstance()?
Manfred Lotz
ml_news at posteo.de
Sat Aug 15 01:23:42 EDT 2020
I have an object which I could initialize providind an int or a str.
I am not sure which of the following is best to use
- try/except
- if type(int)...
- if isinstance(v, int)
Here a minimal example
def get_id(fromname):
# do something with `fromname`
return 0
def get_name(fromid):
# do something with `fromid`
return "something"
""" For O1, O2, O3: self.myid is int
self.name is str
"""
class O1:
def __init__(self, val):
try:
self.myid = int(val)
self.name = get_name(self.myid)
except:
self.myid = get_id(val)
self.name = val
class O2:
def __init__(self, val):
if type(val) == int:
self.myid = val
self.name = get_name(self.myid)
else:
self.myid = get_id(val)
self.name = val
class O3:
def __init__(self, val):
if isinstance(val, int):
self.myid = val
self.name = get_name(self.myid)
else:
self.myid = get_id(val)
self.name = val
--
Manfred
More information about the Python-list
mailing list