On Mon, Oct 3, 2011 at 12:54, Greg Ewing greg.ewing@canterbury.ac.nz wrote:

The big difference as I see it is that, very often, failing to find something in a dict is not an error, but an entirely normal occurrence. On the other hand, passing something that isn't a valid int representation to int() is most likely the result of a user entering something nonsensical. In that case, the principle that "errors should not pass silently" applies.

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))

It's a little shorter and seems easier to read to me (less repetition).

Cheers,

Dirkjan