Skip to content

Instantly share code, notes, and snippets.

@sujeetkv
Last active July 6, 2019 02:29
Show Gist options
  • Select an option

  • Save sujeetkv/5e53d229fcc73a3f20cea1a7d2c22cdc to your computer and use it in GitHub Desktop.

Select an option

Save sujeetkv/5e53d229fcc73a3f20cea1a7d2c22cdc to your computer and use it in GitHub Desktop.

Revisions

  1. sujeetkv revised this gist Jul 6, 2019. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions usage_example.py
    Original file line number Diff line number Diff line change
    @@ -5,3 +5,4 @@ class MyDict(DictObject):
    d = MyDict(one=1, two=2)

    print(d.one)
    print(d['one'])
  2. sujeetkv created this gist Jun 6, 2019.
    18 changes: 18 additions & 0 deletions dict_object.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    class DictObject(dict):
    """Dict behaving like an object, with attribute-style access."""

    __strict_attr__ = True
    __attr_default__ = None

    def __getattr__(self, name):
    try:
    return self[name]
    except KeyError:
    if self.__strict_attr__:
    raise AttributeError(name)
    else:
    return self.__attr_default__

    def __setattr__(self, name, value):
    if name not in ('__strict_attr__', '__attr_default__'):
    self[name] = value
    7 changes: 7 additions & 0 deletions usage_example.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    class MyDict(DictObject):
    pass


    d = MyDict(one=1, two=2)

    print(d.one)