0
votes

My question relates to how to define an optional parameter which can be of different types (polymorphic).

I was trying to define a wrapper around functools.reduce in python 3.x, and noticed that there is an optional parameter ,[initializer]. I tried to define the same optional parameter, but don't know how. Search around shows that I can generally do something like:

def info(object, spacing=10, collapse=1):

But in this context, the initializer can be many different types with different default values. For example, it can be 0 for addition (as the reduce function) and "" (empty string) for string concatenation. How should I define this parameter?

1
It's not uncommon (but generally ill-advised) to expect and handle different types of argument in Python, e.g. if type(var) is str: do_stuff. - leongold
It's not uncommon (but generally ill-advised) to expect and handle different types of argument in Python@zamuz Alright. But this is standard python library function (reduce). - tinlyx
would you please make clear what you are trying to achieve? The parameter type is determined at runtime (i.e. you never define the parameter type) . It would be quite helpful to see the actual result vs the expected one - ProfHase85
@tinlyx: The pydoc of functools.reduce has reduce(function, sequence[, initial]) -> value, with [, initial] being "placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty." The type for initial does not modify/control the behavior of reduce based on its own contents/type. - code_dredd
@ProfHase85 As in the OP, I am trying to provide a wrapper of the reduce function. - tinlyx

1 Answers

1
votes

So what about simply?

def reduce_wrapper(custom_param, function, iterable, *args):
    # do stuff
    reduce(function, iterable, *args)