[Python] What is the right way to handle "key or value" arguments to a dict?

Discussão em 'Python' iniciado por Stack, Maio 20, 2025.

  1. Stack

    Stack Membro Participativo

    Say we have an object that is meant to facilitate the use of arrays, and has some internal storage.

    Say we have a method that is supposed to do something. For instance, you may have to feed it "volume". I think it's fairly intuitive that you may just want to check if the data array already exists in internal memory, ELSE use an array that was sent when the function was called.

    I was curious whether the standard way to do this was

    a) Don't do this at all, have different callables

    b) Try/Except or If/Else structure

    c) dict.get(keyorarray, keyorarray) (This tries for key, and on failure returns the object)

    example:

    class Spheres(object):

    def __init__(self):
    self._dict = dict()

    def volumes(self, radii='radii'):
    return (4/3) * math.pi * self._dict.get(radii, radii)**3


    The idea being that I can either handle my arrays manually, keeping track of them in the namespace of the script, or that for certain cases I can embed them into the object (ie: spheres['radii'] = radii), and then instead of calling spheres.volumes(spheres['radii']) i can call spheres.volumes() OR spheres.volumes(radii).

    Basically I want to offer the option, but if the user is storing a bunch of vectors in the object I want to allow the algorithms to be 'smart' and just use the data that they already have available.

    Continue reading...

Compartilhe esta Página