Skip to main content

An abstract class to enable abitrary classes to define their own dictionary representation.

Project description

Python Dictionary Representation

Description

The DictRepr class is an abstract base class that enables any subclass to define its own dictionary representation. This makes it possible to do:

dict_repr = dict(arbitrary_object)

The subclass only needs to do two things:

  • Override the keys() instance method to return a list of strings
  • Have the keys map to variables or properties on that object

Example

lass MyArbitraryClass(DictRepr):

    _keys = ["uppercase", "length"]

    def __init__(self, value: str):
        self._value = value

    @property
    def uppercase(self):
        return self._value.upper()

    @property
    def length(self):
        return len(self._value)

    def keys(self):
        return self._keys


if __name__ == "__main__":
    myobj = MyArbitraryClass("Hello World")
    mydict = dict(myobj)
    print("mydict type: {}".format(type(mydict)))
    pprint(mydict)
$ python3 examples/dict_repr_example.py
mydict type: <class 'dict'>
{'length': 11, 'uppercase': 'HELLO WORLD'}

Mapping Keys to Object Attributes

It may be the case that a desired dicitonary key isn't the name of the corresponding attribute. For example, a string may have spaces or other characters that, while perfectly suitable as a dictionary key, make it illegal as an object attribute name.

In this case, the KeyTuple class provides a mapping between key string and attribute name. Simply include a KeyTuple object in place of the key string:

_keys = [
    KeyTuple("string with spaces 1", "no_spaces_1"),
    KeyTuple("string with spaces 2", "no_spaces_2")
]

KeyTuple Example

Let's modify the previous example:

from py_dict_repr import DictRepr, KeyTuple
class MyArbitraryClass(DictRepr):

    _keys = [
        KeyTuple("uppercase verion", "uppercase"),
        KeyTuple("string length", "length"),
        # KeyTuple may be mixed with regular key strings
        "lowercase"
    ]

    def __init__(self, value: str):
        self._value = value

    @property
    def uppercase(self):
        return self._value.upper()

    @property
    def lowercase(self):
        return self._value.lower()

    @property
    def length(self):
        return len(self._value)

    def keys(self):
        return self._keys


if __name__ == "__main__":
    myobj = MyArbitraryClass("Hello World")
    mydict = dict(myobj)
    print("mydict type: {}".format(type(mydict)))
    pprint(mydict)
$ python3 examples/dict_repr_example.py
python3 ./examples/dict_repr_keytuple_example.py
mydict type: <class 'dict'>
{string length: 11, uppercase verion: 'HELLO WORLD', 'lowercase': 'hello world'}

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

py-dict-repr-0.2.0b1.tar.gz (4.8 kB view details)

Uploaded Source

Built Distribution

py_dict_repr-0.2.0b1-py3-none-any.whl (5.7 kB view details)

Uploaded Python 3

File details

Details for the file py-dict-repr-0.2.0b1.tar.gz.

File metadata

  • Download URL: py-dict-repr-0.2.0b1.tar.gz
  • Upload date:
  • Size: 4.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.10.1 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for py-dict-repr-0.2.0b1.tar.gz
Algorithm Hash digest
SHA256 30d8b0253ffc78d7166d6a27ad0b43384211db62d8da1dba3b10d5b034b40642
MD5 e614f0d2c704268804026e49371d9b75
BLAKE2b-256 fc3519f572d36cc4739d140cc8d4db5aa70f9139dfce05d1a098f6d69fea8c78

See more details on using hashes here.

File details

Details for the file py_dict_repr-0.2.0b1-py3-none-any.whl.

File metadata

  • Download URL: py_dict_repr-0.2.0b1-py3-none-any.whl
  • Upload date:
  • Size: 5.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.10.1 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for py_dict_repr-0.2.0b1-py3-none-any.whl
Algorithm Hash digest
SHA256 937774e2a168191bcd2de10b6ff12359fa255bb4c2b141467a768d82d440f368
MD5 26d5b7bb9c6868f7d03b2d96947d38e9
BLAKE2b-256 aaee99a3d9205fe9d8e2837a2c4eb312e738861c0385d218dd509396271e844c

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