Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Vincent Zamora
Vincent Zamora
3,872 Points

Dictionary Comprehensions

I am trying to figure out what this code does, but I am not having any luck:

fields: Dict[str, DataMember] = {x: getattr(cls, x, None) for x in dir(cls) if isinstance(getattr(cls, x, None), DataMember)}

[MOD: added ```python formatting. -cf]

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

Rewriting the original code:

fields: Dict[str, DataMember] = {x: getattr(cls, x, None) for x in dir(cls) if isinstance(getattr(cls, x, None), DataMember)}

as

fields: Dict[str, DataMember] = {x: getattr(cls, x, None)
                                for x in dir(cls)
                                if isinstance(getattr(cls, x, None), DataMember)
                               }

the elements:

  • dir(cls) returns a list of attributes of cls
  • for x in dir(cls) cycles over this list assigning the attribute name to x
  • getattr(cls, x, None) retrieves the value of the attribute, if it exists, or returns None
  • isinstance(object, Class) returns True if object is an instance of Class.
  • Together, isinstance(getattr(cls, x, None), DataMember) returns True if the attribute x contains an instance of class DataMember
  • finally, x: getattr(cls, x, None) associates key name x with the object attribute x if it is an instance of DataMember

Post back if you need more help. Good luck!