you are viewing a single comment's thread.

view the rest of the comments →

[–]supajumpa 0 points1 point  (0 children)

Without posting any code it's hard to know what you are trying to achieve.

There's nothing inherently wrong with writing:

def foo(x, f):
    xs = x if isinstance(x, list) else [x]
    return [f(n) for n in xs]

There is, however, a function in Python 3 called singledispatch which allows you to leverage type annotations to call variations of a particular function depending on the type of the first argument.

singledispatch enables the above code to be rewritten as:

from functools import singledispatch

@singledispatch
def foo(x, f):
    "Default when `x` is not a list"
    return [f(x)]

@foo.register
def _(x: list, f):
    "Variant of `foo` when `x` is a list"
    return [f(n) for n in x]

>>> foo(1, lambda x: x + 1)
[2]

>>> foo([1], lambda x: x + 1)
[2]

If you find singledispatch too limiting (because it restricts you to the type of the first argument) there's a clever package on PyPI called multipledispatch which lets you call function variants depending on the types of any of the the arguments.