Subclassing List

Build a list that can be prefilled with a certain number of numbers.

filledlist.py
import copy

class FilledList(list):
    def __init__(self, count, value, *args, **kwargs):
        super().__init__()
        for _ in range(count):
            self.append(copy.copy(value))

Testing

>>> import filledlist
>>> fl = filledlist.FilledList(9, 2)
>>> len(fl)
9
>>> fl
[2, 2, 2, 2, 2, 2, 2, 2, 2]
>>> fl2 = filledlist.FilledList(2, [1, 2, 3])
>>> fl2
[[1, 2, 3], [1, 2, 3]]
>>> fl2[0][1] = 5
>>> fl2
[[1, 5, 3], [1, 2, 3]]

_
This underscore ignores the number that would come out of range. I could just use like x and then never use x there. But underscore is cleaner and implies that you don’t care about this value.

copy.copy(value)
Why use copy.copy?
If they send in something mutable, like say, another list, each member in that filled list or each member in our filled list that was a copy of that list would be the same member if we weren’t using copy.copy.

If you changed one of them it would change all of the others too because we’re just putting in references to that list.


Subclassing Dict

class JavaScriptObject(dict):
    def __getattribute__(self, item):
        try:
            return self[item]
        except KeyError:
            return super().__getattribute__(item)

__getattribute__
This method is used whenever we ask for an attribute using the dot notation, in our case, from a dict object.

In our program, we overrode it to use the key following the dot as a dictionary key and get us the value, otherwise it would work the old-fashioned way and get us the attribute. If neither exists, it would give an error of course.

Testing

>>> jso = JavaScriptObject({'name': 'Kenneth'})
>>> jso.language = 'Python'
>>> jso.name
'Kenneth'
>>> jso.language
'Python'
>>> jso.fake
KEYERROR!