1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] How to "perfectly" override a dict?

Discussão em 'Python' iniciado por Stack, Setembro 13, 2024.

  1. Stack

    Stack Membro Participativo

    How can I make as "perfect" a subclass of dict as possible? The end goal is to have a simple dict in which the keys are lowercase.

    It would seem that there should be some tiny set of primitives I can override to make this work, but according to all my research and attempts it seem like this isn't the case:


    Here is my first go at it, get() doesn't work and no doubt there are many other minor problems:

    class arbitrary_dict(dict):
    """A dictionary that applies an arbitrary key-altering function
    before accessing the keys."""

    def __keytransform__(self, key):
    return key

    # Overridden methods. List from
    # https://stackoverflow.com/questions/2390827/how-to-properly-subclass-dict

    def __init__(self, *args, **kwargs):
    self.update(*args, **kwargs)

    # Note: I'm using dict directly, since super(dict, self) doesn't work.
    # I'm not sure why, perhaps dict is not a new-style class.

    def __getitem__(self, key):
    return dict.__getitem__(self, self.__keytransform__(key))

    def __setitem__(self, key, value):
    return dict.__setitem__(self, self.__keytransform__(key), value)

    def __delitem__(self, key):
    return dict.__delitem__(self, self.__keytransform__(key))

    def __contains__(self, key):
    return dict.__contains__(self, self.__keytransform__(key))


    class lcdict(arbitrary_dict):
    def __keytransform__(self, key):
    return str(key).lower()

    Continue reading...

Compartilhe esta Página