Dict Comprehensions - PEP 274

Jack Diederich jack at performancedrivers.com
Wed Feb 5 00:33:18 CET 2003


On Tue, Feb 04, 2003 at 04:52:59PM -0600, Donnal Walter wrote:
> 1. Is ``PEP 274 -- Dict Comprehensions`` still under active consideration?
> If so, what is its present status?

dunno, I emailed the author once and got no response...
 
> 2. Is there currently (under 2.2.2 or 2.3) a more elegant way to accomplish
> the following:
> 
> class _node(object): pass
> 
> class Cell(_node): pass
> 
> class Assembly(_node):
> 
>     def __getstate__(self):
>         state = {}
>         for name, attr in self.__dict__.items():
>             if isinstance(attr, _node):
>                 state[name] = attr
>         return state
> 

For personal stylistic reasons I would keep the state up-to-date
with add_node(), del_node() methods on the object.  There isn't a
faster or clearer way to do it than what you have above, but if 
you like the look better you can do it with a list comprehension 

state = dict([[name, attr] for (name, attr) in self.__dict__.items() if isinstance(attr, _node)])

or if you want a pure-functional way that is more comfy for LISPers [guilty]

state = dict(filter(lambda pair:isinstance(pair[1], _node), self.__dict__.items()))

The list comprehension is more popular on c.l.p than filter(), but I'll go 
on record as preferring the filter.  That is a seperate flamewar over
which left to right reading you like best

# list comprehensions
[_result_ for _item_ in _list_ if _test_]

# filter, with labmda
[filter lambda _item_:_test_, _list_]

-jackdied





More information about the Python-list mailing list