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'}

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.1.0.dev0.tar.gz (2.6 kB view details)

Uploaded Source

File details

Details for the file py-dict-repr-0.1.0.dev0.tar.gz.

File metadata

  • Download URL: py-dict-repr-0.1.0.dev0.tar.gz
  • Upload date:
  • Size: 2.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/46.0.0 requests-toolbelt/0.9.1 tqdm/4.40.2 CPython/3.7.7

File hashes

Hashes for py-dict-repr-0.1.0.dev0.tar.gz
Algorithm Hash digest
SHA256 835058d6a1270f89fd933dbd2a6ab9a4e7e99e0b29c21840cb809eb355001952
MD5 a950397adcbbf946c4caa4c4097f3afe
BLAKE2b-256 76799e694a522b2220f9b268467cef87ee35aef19ea593f2749966017db57546

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