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 trialVincent Zamora
3,872 PointsDictionary 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
Treehouse Moderator 68,454 PointsRewriting 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 ofcls
-
for x in dir(cls)
cycles over this list assigning the attribute name tox
-
getattr(cls, x, None)
retrieves the value of the attribute, if it exists, or returnsNone
-
isinstance(object, Class)
returnsTrue
ifobject
is an instance of Class. - Together, isinstance(getattr(cls, x, None), DataMember) returns
True
if the attributex
contains an instance of class DataMember - finally,
x: getattr(cls, x, None)
associates key namex
with the object attributex
if it is an instance ofDataMember
Post back if you need more help. Good luck!
Vincent Zamora
3,872 PointsAwesome! Thank you!