Pythonic/idiomatic?

Tim Chase python.list at tim.thechases.com
Tue Nov 9 02:40:32 CET 2010


On 11/08/10 18:34, Seebs wrote:
> On 2010-11-09, Ben Finney<ben+python at benfinney.id.au>  wrote:
>>      ' '.join(x for x in target_cflags.split() if re.match('^-[DIiU]', x))
>
> Ahh, handy.
...
>> The latter works only in Python with set literals (Python
>> 2.7 or later).
>
> I think we're stuck with backwards compatibility at least as
> far as 2.4.
>
> No, I'm not kidding. *sigh*

I feel your pain :)  At least be glad you don't have to go back 
to 2.3 where Ben's suggested generator-syntax isn't available.

>> 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'])
>
> The regex is intentionally not anchored with a $, because I'm looking
> for "starts with", not "is".

I suppose you could do

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

or

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

or even

   ' '.join(
       x for x in target_cflags.split()
       if x[:1] == '-' and x[1:2] in 'DIiU'
       )

-tkc







More information about the Python-list mailing list