How can I parse this correctly?

Chris Angelico rosuav at gmail.com
Sun Apr 6 04:32:23 EDT 2014


On Sun, Apr 6, 2014 at 6:16 PM, Ben Finney <ben+python at benfinney.id.au> wrote:
>> print int(row['YEAR'] or 0000)
>
> “foo or bar” is not a Pythonic way to get a default value; it relies on
> quirks of implementation and is not expressive as to the meaning you
> intend.
>
> Rather, be explicit:
>
>     # Default to the beginning of the project.
>     year = 1969
>     if row['YEAR']:
>         # Use the value as a text representation of a year.
>         year = int(row['YEAR'])

What's wrong with "foo or bar" as a means of defaulting a blank
string? (Obviously this assumes you know you have a string, as it'll
equally default a 0 or a 0.0 or a [] or anything else false.) The
definition of the "or" operator is that it returns its first argument
if it's true, otherwise it returns its second argument. That's not a
quirk of implementation. This exact example (with strings, no less!)
can be found in help("or") and in the docs:

https://docs.python.org/3/reference/expressions.html#boolean-operations

ChrisA



More information about the Python-list mailing list