|

Is it a bird? Is it a plane? Nah – just a Python class behaving like a dictionary.

For a container class with a dictionary with config values (among other members) I wanted easy reading access as if it was a dict itself. For that you only have to implement the __getitem__ method.

class MyPseudoDataClass:
    def __init__(self, values: {}, name: str) -> None:
        self._values = values
        self.name = name # just to show it can also contain other members

d = MyPseudoDataClass({'sensor_pin': 2}, 'My name')

print(d.values['sensor_pin']) # this felt too long - I wanted d['sensor_pin']

# output is 2
class MyPseudoDataClass:
    def __init__(self, values: {}, name: str) -> None:
        self._values = values
        self.name = name # just to show it can also contain other members

    def __getitem__(self, name):
        return self._values[name] # provides access to dict['key']

d = MyPseudoDataClass({'sensor_pin': 2}, 'My name')

print(d['sensor_pin'])

# output is 2

You can extend the provided dict functionality for your class if needed like the following:
All but the update method was professionally copy and pasted from stackoverflow.

class MyPseudoDataClass:
    def __init__(self, values: {}, name: str) -> None:
        self._values = values
        self.name = name # just to show it can also contain other members

    def __getitem__(self, name):
        return self._values[name] # provides access to dict['key']

    def __iter__(self):
        return iter(self._values) # access to iterator for use in loops / comprehensions

    def keys(self):
        return self._values.keys() # list of the dict keys

    def items(self):
        return self._values.items() # list of tuples containing key and value pairs

    def values(self):
        return self._values.values() # list of the values

    # updates the existing dict with new one
    # new items are added, values of existing keys overwritten
    def update(self, update: {}):
        self._values.update(update)

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.