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

David Townshend aquavitae69 at gmail.com
Mon Oct 3 14:39:52 CEST 2011


>
> Important consideration: Would the default value be typechecked or
> not? (i.e. Does something like `float(s, {})` raise TypeError?)
> It's not uncommon to use None as the result value when the input is
> invalid, but not typechecking would then leave the door open to
> strangeness like my example.
> Or would None just be inelegantly special-cased, or...?
> This could be one of those instances where Python is better off
> leaving people to write their own short one-off functions to get the
> /exact/ behavior desired in their individual circumstances.


I would suggest not checking type for exactly that reason.  One-off
functions are fine if they are one-off, but most cases where this behaviour
is needed the one-off function is exactly the same is every case.

 I don't think David is arguing for the default behavior to change -- merely
> that you get a dict.get style default. Kinda similar to getattr/2 raising
> AttributeError, and getattr/3 returning the default value.


Yes, dict.get is exactly the sort of thing I was going for.  I think that
there are also a few other methods dotted throughout the stdlib that have
this an optional "default" argument like this, so this isn't really a new
idea, it's only new in as it applies to int and float.

pv = float(ln['PV']) if ln['PV'] else None
> pv = float(ln['PV'], default=None)


I wouldn't implement it this way because of the problems already pointed
out.  I would use a try statement (as in my first example), which would be
more robust, but which cannot be written as a one-liner.  If you were to
write your example in a series of try statements, it would end up four times
longer and much less readable!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20111003/59bfa62e/attachment.html>


More information about the Python-ideas mailing list