Pythonic/idiomatic?

Ben Finney ben+python at benfinney.id.au
Mon Nov 8 19:26:53 EST 2010


Seebs <usenet-nospam at seebs.net> writes:

> I have a similar situation in a Python context, and I am wondering
> whether this is an idiomatic spelling:
>
> 	' '.join([x for x in target_cflags.split() if re.match('^-[DIiU]', x)])
>
> This appears to do the same thing, but is it an idiomatic use of list
> comprehensions, or should I be breaking it out into more bits?

One thing to know is that, if you want to create a sequence whose only
purpose is to feed to something else and then throw away, a generator
will be cleaner and (probably) better performing than a list.

For this purpose, there is a generator expression syntax
<URL:http://docs.python.org/reference/expressions.html#generator-expressions>,
almost identical to a list comprehension except without the enclosing
brackets.

    ' '.join(x for x in target_cflags.split() if re.match('^-[DIiU]', x))

The regex is less clear for the purpose than I'd prefer. For a simple
“is it a member of this small set”, I'd find it more readable to use a
simple list of the actual strings::

    ' '.join(
        x for x in target_cflags.split()
        if x in ['-D', '-I', '-i', '-U'])

or even an actual set::

    ' '.join(
        x for x in target_cflags.split()
        if x in {'-D', '-I', '-i', '-U'})

The latter works only in Python with set literals (Python 2.7 or later).

-- 
 \      “I find the whole business of religion profoundly interesting. |
  `\     But it does mystify me that otherwise intelligent people take |
_o__)                                    it seriously.” —Douglas Adams |
Ben Finney



More information about the Python-list mailing list