Miikka
Miikka

Reputation: 4653

What's the difference between attr.asdict(x) and x.__dict__?

In Python, when you want a dict of the attributes of your attrs-enhanced class, what's the difference between using __dict__ and attr.asdict()? Which one should you use? For example, in this example they have the same result:

import attr

@attr.s(auto_attribs=True)
class MyClass:
  x: str

value = MyClass(x="hello")
print(value.__dict__)
# {'x': 'hello'}
print(attr.asdict(value))
# {'x': 'hello'}

Upvotes: 0

Views: 1238

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

__dict__ is an implementation attribute that only stores per-instance "direct" attributes (so properties or other computed attributes won't be found there). And it only exists for dict-based types - slots-based one don't have a dict at all.

attrs.asdict OTHO uses the type's metadata to get the list of attributes names (so it will work on slot-based classes), uses getattr() to get the values (so it will correctly retrieve computed attributes), can recurse on attributes that are "attrs-enabled", etc. But it will, of course, only work on attrs-enabled types...

Upvotes: 4

Related Questions