Dict Comprehensions - PEP 274

David Eppstein eppstein at ics.uci.edu
Tue Feb 4 18:18:34 EST 2003


In article <mailman.1044399252.24845.python-list at python.org>,
 "Donnal Walter" <donnalcwalter at yahoo.com> wrote:

> 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

Since you were asking about dict comprehensions, maybe you'd at least 
prefer a list comprehension solution:

def __getstate__(self):
    return dict([(name,attr) for name, attr in self.__dict__.items() if 
isinstance(attr, _node)])

(Warning, not tested...)

-- 
David Eppstein       UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/




More information about the Python-list mailing list