[Python-ideas] Default return values to int and float

Julian Berman julian at grayvines.com
Mon Oct 3 15:35:49 CEST 2011


> Hmm, not really true in my experience. Here's some actual code from my
> codebase at work:
>
> v = float(row[dat]) if row[dat] else 0.0
> d.append(float(row[t]) if row[t] else 0.0)
> gen = (float(i) if i != '.' else None for i in row[1:])
> limits = [(float(i) if i != '.' else None) for i in ln[5:15]]
> line[i] = (None if line[i] == '.' else float(line[i]))
> ls.append(float(row[i]) if row[i] else None)
> data[row['s']] = float(val) if '.' in val else int(val)
> cur.append(float(ln[f]) if ln[f] else None)
> cur.append(float(ln['DL']) if ln['DL'] else None)
> pv = float(ln['PV']) if ln['PV'] else None
> mgn = float(ln['MGN']) if ln['MGN'] else None
> f = lambda x: float(x) if x else 1
> data[sn] += float(row['PC']) if row['PC'] else 0.0, row['PCC']
> ubsc = 1 if not row['CSCALE'] else float(row['CSCALE'])
> scale = float(row['ESCALE']) if row['ESCALE'] else 1.0
> efp = float(row['FSCALE']) if row['FSCALE'] else 1.0
> convert = lambda x: float(x) if x else None
>
> In other words, this happens a lot in code where you deal with data
> from a third party that you want to convert to some neater structure
> of Python objects (in cases where a null value occurs in that data,
> which I would suggest is fairly common out there in the Real World).
> Throwing a ValueError is usually not the right thing to do here,
> because you still want to use all the other data that you got even if
> one or two values are unavailable.
>
> Converting two of the above examples:
>
> pv = float(ln['PV']) if ln['PV'] else None
> pv = float(ln['PV'], default=None)
>
> d.append(float(row[t]) if row[t] else 0.0)
> d.append(float(row[t], default=0.0))
>

This is one of the cases that I typically just use logical or for if I'm
expecting some nonzero but false thing, which is reasonably readable.

     v = float(row[t] or 0)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20111003/3c58a818/attachment.html>


More information about the Python-ideas mailing list