python - How do I name a function that takes an object `A` and a set `{A, B}` as arguments, then returns `B`? -
what name following function (as implemented in python)?
def a_function(element, a_set): if a_set[0] == element: return a_set[1] if a_set[1] == element: return a_set[0] assert 'a' == a_function('b', ['a', 'b'])
i use different function name, different argument names , docstring make clear what's going on, like:
def get_other(current, both): """return element 'both' not 'current'.""" ...
note both
implies pair without long-winded, , doesn't specify type
required.
you can use own implementation or joel's; long function says, doesn't matter how it's implemented (barring performance concerns, edge cases, etc.).
however, work non-indexable containers (like set
, or keys of dict
) without having explicitly test both
is, go for:
def get_other(current, both): """return element 'both' not 'current'.""" item in both: if item != current: return item
indeed, if len(both) > 2
, return first item in isn't equal current
- can add checks if not desired behaviour.
Comments
Post a Comment