Skip to main content

Yet another Attribute Dict implementation !

Project description

Attr-Dict

Yet another Attribute Dict implementation !

This package provides a dictionary with attribute access to keys. It is especially convenient when working with deeply nested data. (Original idea from https://github.com/otsaloma/attd)

Different implementations based on OrderedDict:

  • Strict: AttrDict
    Work as a dictionary with class attribute syntax. Some keys cannot be translated to attributes (like int), in this case revert to usual dict syntax (ie: dict[key]).

  • Lazy: LazyAttrDict
    Based on AttrDict but return None on missing keys, and mask values (list of keys on repr()).

  • Restricted: RestrictedAttrDict
    Lazy Attribute dictionary enforcing value change from dictionary syntax only (setitem & delitem), and masking values (return list of keys on repr()).

    Will raise AttributeError on Attribute change (setattr or delattr) to mimic @property attribute.

Basic usage:

# Some dict
>>> conf_A = {'a': 1, 'b': 2, 'c': 3}
>>> conf_B = {'a': 11, 'b': 12, 'c': {'c1': 13, 'c2': 23}}

# import library
>>> from attr_dict import AttrDict, LazyAttrDict, RestrictedAttrDict


## Create a Lazy Attribute Dict
>>> lad = LazyAttrDict()

# Add some data (using different syntax)
>>> lad.A = conf_A
>>> lad['B']= conf_B

# or
>>> lad.update(dict(A=conf_A, B=conf_B))

# Access data
>>> lad
{'A': {'a': 1, 'b': 2, 'c': 3}, 'B': {'a': 11, 'b': 12, 'c': {'c1': 13, 'c2': 23}}}
>>> lad.A
{'a': 1, 'b': 2, 'c': 3}
>>> lad.A.c
3
>>> lad['A']['c']
3
>>> 'c' in lad.A
True

Other features:

# Export to JSON
>>> json_data = lad.to_json()
>>> print(json_data)
{
  "A": {
    "a": 1,
    "b": 2,
    "c": 3
  },
  "B": {
    "a": 11,
    "b": 12,
    "c": {
      "c1": 13,
      "c2": 23
    }
  }
}

## Import JSON to a new Attribute Dict
>>> new_ad = AttrDict().from_json(json_data)
>>> print(new_ad)
AttrDict([('A', AttrDict([('a', 1), ('b', 2), ('c', 3)])), \
('B', AttrDict([('a', 11), ('b', 12), ('c', AttrDict([('c1', 13), ('c2', 23)]))]))])


## Use Restricted Attribute Dict
>>> rad = RestrictedAttrDict()

# Add data using dict syntax (setitem)
>>> rad['A'] = {}
>>> rad['A']['a'] = 1
>>> for k,v in conf_A.items():
...     rad['A'][k] = v
...

# Data access to values is restricted
>>> rad
['A']
>>> rad.A
['a', 'b', 'c']
>>> rad.A.b
2
>>> dict(rad.A)
{'a': 1, 'b': 2, 'c': 3}


# Attributes are protected
>>> rad.A = conf_A                              # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: can't set attribute

>>> rad.A.b = 0                                 # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: can't set attribute
>>> del rad.A.b                                 # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: can't delete attribute

# Use dict syntax to change or delete
>>> rad.A['b'] = 0
>>> rad.A.pop('b')
0

# Missing key return None
>>> print(rad.A.b)
None
>>> 'b' in rad.A
False

Relative interfaces named 'indexes' are also available to manage any king of objects with these attribute dictionaries:
AttrIndex, LazyIndex, RestrictedIndex
(current implementation only works on 2 levels)

Index usage:

# Import & init
>>> from attr_dict import LazyIndex
>>> x = LazyIndex()

# set keys & args
>>> x.set_arg('A', a=1, b=2, c=3)
>>> x.set_key('B')

>>> x.index
{'A': {'a': 1, 'b': 2, 'c': 3}, 'B': {}}

# get, del & check
>>> x.get_key('A')
{'a': 1, 'b': 2, 'c': 3}
>>> x.get_arg('A', 'b')
2

>>> x.del_arg('A', 'c')
>>> x.get_key('A')
{'a': 1, 'b': 2}

>>> x.check_arg('A', 'b', 2)
True

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

Attr-Dict-1.0.0.tar.gz (4.6 kB view details)

Uploaded Source

Built Distribution

Attr_Dict-1.0.0-py3-none-any.whl (6.3 kB view details)

Uploaded Python 3

File details

Details for the file Attr-Dict-1.0.0.tar.gz.

File metadata

  • Download URL: Attr-Dict-1.0.0.tar.gz
  • Upload date:
  • Size: 4.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.1

File hashes

Hashes for Attr-Dict-1.0.0.tar.gz
Algorithm Hash digest
SHA256 3378d2e5a329fc084840c8644cd3759764016ec2f9e0d7cd4307f1a909597f4e
MD5 f611c82336b5ebbff99e68f641992bcf
BLAKE2b-256 62540e75a87fe1449052e6ed5740fedeeda2cd0adba0305a3a0fe9ccc707174b

See more details on using hashes here.

File details

Details for the file Attr_Dict-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: Attr_Dict-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 6.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.1

File hashes

Hashes for Attr_Dict-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6fcb77fb2dc9336a2a34357810ba2ea964cbeb28dafc070975cb75c5844f1cc6
MD5 e5c8573688db451e339550fd15f208aa
BLAKE2b-256 0638431d442ceb2a25d2732b98ecb272875d8639e9a48f8569afe5c2ec76861b

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page