Dictobj

This is an object that behaves like both an object (dot notation access to attributes) and like a dictionary (square bracket notation access to attrs).

It is a subclass of dict and has is_dict set to True.

It will also generate an __init__ for you based on what you specify as the fields attribute.

class MyAmazingKls(dictobj):
    fields = ["one", "two", ("three", 4)]

Creates an __init__ that behaves like:

def __init__(self, one, two, three=4):
    self.one = one
    self.two = two
    self.three = three
fields

Must be an iterable of strings where each string is a valid variable name.

Or a tuple of (<variable_name>, <dflt_value>) where the <dflt_value> is used if that variable is not passed into __init__.

Because it must be an iterable, it can also be a dictionary where the values are docstrings for the attributes!

class MyAmazingKls(dictobj):
    fields = {
          "one": "The first argument"
        , "two": "The second argument"
        , ("three", 4): "Optional third argument"
        }

Is a perfectly valid example.

Internally, dictobj uses a library called namedlist to validate the fields and work out the default values when an option isn’t specified.

Once an instance of dictobj is created you may access the attributes however you wish!

instance = MyAmazingKls(one=1, two=2)

instance.one == 1
instance["one"] == 1

instance.three == 4

list(instance.items()) == [("one", 1), ("two", 2), ("three", 4)]

instance.as_dict() == {"one": 1, "two": 2, "three": 4}
class input_algorithms.dictobj.dictobj(*args, **kwargs)
__getattr__(key)

Pretend object access

__getitem__(key)

If the key is on the class, then return that attribute, otherwise do a super call to dict.__getitem__.

__nonzero__()

Dictionaries are Falsey when empty, whereas we want this to be Truthy like a normal object

__setattr__(key, val)

If the key is on the class already, then set the value on the instance directly.

We also do the equivalent of dict.__setitem__ on this instance.

__setitem__(key, val)

If the key is on the class itself, then set the value as an attribute on the class, otherwise, use a super call to dict.__setitem__ on this instance.

as_dict(**kwargs)

Return as a deeply nested dictionary

This will call as_dict on values if they have such an attribute.

clone()

Return a clone of this object