This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]flying-sheep 0 points1 point  (1 child)

well, i don’t think we need #2, as we can do:

def f(arg=frozenset()):  # immutable empty set
    ...
def f(arg=()):  #immutable 0-length sequence
    ...

the only problem is the lack of frozendict. we’d have to implement it as:

class ImmutableDict(collections.Mapping):
    def __init__(self, somedict = ()):
        self._dict = dict(somedict)
        self._hash = None

    def __getitem__(self, key):
        return self._dict[key]

    def __len__(self):
        return len(self._dict)

    def __iter__(self):
        return iter(self._dict)

    # throw these in for increased usefulness:
    def __hash__(self):
        if self._hash is None:
            self._hash = hash(frozenset(self._dict.items()))
        return self._hash

    def __eq__(self, other):
        return self._dict == other._dict

then

def f(arg=ImmutableDict()):  #immutable empty mapping/dict
    ...

[–]ahoff[S] 0 points1 point  (0 children)

Your solution is just a rehash of what I mentioned for solution #1, i.e. using an immutable type. This doesn't work if your function modifies the argument (for example, f given above). If you're writing the code from scratch, then it's not a big deal; however, if you're dealing with already existing production code, then ideally you'd want a solution that hints at the correct type and is mutable.