Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #69758

Re: How can I parse this correctly?

References <CAJUMiQsoNbNzDgUOkaQxFLGptTqKriD7DcXSeFwwu_-v4TKJKQ@mail.gmail.com> <85zjjz141k.fsf@benfinney.id.au> <985B907F-8EC7-4B5C-8A9F-64AEC3E5803D@gmail.com> <85lhvi27qh.fsf@benfinney.id.au>
Date 2014-04-06 18:32 +1000
Subject Re: How can I parse this correctly?
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.8945.1396773151.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Sun, Apr 6, 2014 at 6:16 PM, Ben Finney <ben+python@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: How can I parse this correctly? Chris Angelico <rosuav@gmail.com> - 2014-04-06 18:32 +1000

csiph-web