Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!nntp.club.cc.cmu.edu!micro-heart-of-gold.mit.edu!bloom-beacon.mit.edu!bloom-beacon.mit.edu!panix!roy From: Roy Smith Newsgroups: comp.lang.python Subject: Re: Python Style Question Date: Thu, 30 Oct 2014 20:34:27 -0400 Organization: PANIX Public Access Internet and UNIX, NYC Lines: 40 Message-ID: References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> <54521c8f$0$12982$c3e8da3$5496439d@news.astraweb.com> NNTP-Posting-Host: localhost X-Trace: reader1.panix.com 1414715668 18331 127.0.0.1 (31 Oct 2014 00:34:28 GMT) X-Complaints-To: abuse@panix.com NNTP-Posting-Date: Fri, 31 Oct 2014 00:34:28 +0000 (UTC) User-Agent: MT-NewsWatcher/3.5.3b3 (Intel Mac OS X) Xref: csiph.com comp.lang.python:79981 In article <54521c8f$0$12982$c3e8da3$5496439d@news.astraweb.com>, Steven D'Aprano wrote: > Anton wrote: > > > Let's say I have an incoming list of values *l*. Every element of *l* can > > be one of the following options: > > 1) an integer value > > 2) a string in form of '', e.g. '7' > > 3) a string with a json serialization of an integer value, e.g. '"7"' > > 4) something else that should be ignored > > > > I need to transform this list into another list with values from options > > 1)-3) coerced to int. The code below should do this. > > I don't particularly like either version. I prefer this: > > def load_int(obj): > if isinstance(obj, int): > # Case 1), an int, e.g. 7 > return obj > elif isinstance(obj, str): > # Case 2) and 3), a str or JSON serialised int. > # E.g. '7' or '"7"'. > try: > return int(obj) > except ValueError: > return int(json.loads(obj)) > raise TypeError('require int or str, got %s' % type(obj).__name__) Depending on how strictly you're trying to do input validation, the int(json.loads(obj)) may not be what you want. It allows well-formed json encoding floats, for example. And, of course, since >>> isinstance(True, int) True this code accepts booleans. Oh, but wait, that's by design :-)