Pythonic/idiomatic?

Arnaud Delobelle arnodel at gmail.com
Tue Nov 9 02:34:36 EST 2010


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

> I have an existing hunk of Makefile code:
> 	CPPFLAGS = "$(filter -D* -I* -i* -U*,$(TARGET_CFLAGS))"
> For those not familiar with GNU makeisms, this means "assemble a string
> which consists of all the words in $(TARGET_CFLAGS) which start with one
> of -D, -I, -i, or -U".  So if you give it
> 	foo -Ibar baz
> it'll say
> 	-Ibar
>
> 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)])

You can also use the (less favoured) filter:
>>> target_cflags="-ifoo -abar -U -Dbaz".split()
>>> def matches_flags(flags):
...     return re.compile("^-[%s]" % flags).match
... 
>>> ' '.join(filter(matches_flags("DiIU"), target_cflags))
'-ifoo -U -Dbaz'

-- 
Arnaud



More information about the Python-list mailing list