[GRASS-dev] Copying Landsat MTL file(s) inside the cell_misc directory -- Python scripting

Glynn Clements glynn at gclements.plus.com
Wed May 15 09:06:49 PDT 2013


Pietro wrote:

> > I know the following is a pure python question -- still, can someone shed some
> > light on why is there such a difference between
> >
> >     if 'DATE_ACQUIRED' or 'ACQUISITION_DATE' in line:
> >
> > and
> >
> >     if 'DATE_ACQUIRED' in line or 'ACQUISITION_DATE' in line:
> >
> > ?
> 
> Your error is due to the precedence of the operator, what it is really
> written in the first row is:
> 
> if ( ('DATE_ACQUIRED') or ('ACQUISITION_DATE' in line) ):

It's not just the precedence, but also the semantics of the "or" and
"in" operators. If the first expression had been parenthesised
according to the presumed intent of the expression, i.e.:

	if ('DATE_ACQUIRED' or 'ACQUISITION_DATE') in line:

the result would have been equivalent to:

	if 'DATE_ACQUIRED' in line:

as the "or" operator returns the first argument if it is considered
true and the second argument otherwise. As all non-empty strings are
considered true, the "or" operator would have simply returned the
left-hand string, which would be used as the argument to the "in"
operator.

In general: False, None, 0, 0.0, the empty string and any empty
container (list, tuple, set, dictionary) are considered false, while
most other values are considered true (classes can customise their
behaviour by defining __nonzero__ or __len__ methods).

The "in" operator uses the __contains__ method of the right-hand
argument, i.e. "x in y" evalutes "y.__contains__(x)". For lists,
tuples and sets, "x in y" is true if x is an element of the list or
set; for dictionaries, "x in y" is true if x is a key in the
dictionary y. For strings, the expression is true if the left-hand
argument is a substring of the right-hand argument.

If you want to find out whether any one of a number of candidates are
contained within an object, you need to explicitly iterate over them,
e.g.:

	if any(x in line for x in ('DATE_ACQUIRED', 'ACQUISITION_DATE')):

-- 
Glynn Clements <glynn at gclements.plus.com>


More information about the grass-dev mailing list