brownie icon indicating copy to clipboard operation
brownie copied to clipboard

"AttrDict" or "DictyObject"?

Open slacy opened this issue 14 years ago • 1 comments

Hi, what I've often seen (particularly in web frameworks and web templating languages are objects that behave like dicts.

I've got an implementation of said pattern myself, and would be happy to add it to brownie if you think it's something useful. Let me know and I'll craft up a patch and submit a pull request.

slacy avatar Apr 01 '11 19:04 slacy

It's called a "Bunch". If you only need the attributes it exists in the stdlib since 2.7 as argparse.Namespace. I also have an implementation here.

There's some considerations for implementing a Bunch:

  • __dir__: Leave it be, swap it for self.keys() or merge keys and default dir? In the latter case it seems you'll need to reimplement the default behavior because I haven't been able to get it working with any form of "super" calling, but you could just merge keys and __dict__.
  • How to deal with conflicting keys and real attributes. If __dir__ is implemented as a merge it should probably mirror the conflict behavior in the merge.
  • Which exception to raise for missing keys: you could use AttributeError for attribute-access and KeyError for item-access, or you could use one of the two for all types of access depending on which semantics you're after.

dag avatar Jul 26 '11 10:07 dag