0

Suppose you have functions f1: A1 ->B, f2: A2->B, …. Julia has function overloading, so you could define them all as f, and the type A1, A2, … will determine which one gets applied. When encountering this situation in Python, is there any way to avoid having to construct different functions with different names, and as a result probably including some description of input arguments in function names (something like B_from_A1, B_from_A2 , etc.), thereby cluttering the function names?

ashman
  • 154
  • 1
  • 5

1 Answers1

0

Python has a few different ways that you can encapsulate different amounts of arguments into a single function definition.

Arbitrary Arguments:

def foo(*args, **kwargs):
    ...

args and kwargs will be available inside the function. args will be a tuple containing positional arguments in the same order that they are passed into the function. kwargs will be a dict whose key:value mappings will correspond to the name=value keyword arguments passed to the function.

Note: the function can be called without passing anything, in which case both of these structures would be empty.

As well, other parameters can be defined in the function definition, and Python will always pass values for these arguments before the "catch-all" *args and **kwargs.

Example:

def foo(a, b, *args, **kwargs):
    ...

a and b are now required, and anything passed beyond them will be given to *args and **kwargs.

Default Arguments:

Arguments can also be given default values such that you are no longer required to pass a value into them in order to call the function.

def foo(a='test', b='test2')
    ...

Using this pattern, you can simply call foo like so:

>>> foo()

and the function will receive the default values for a and b.

This pattern can be mixed with the previous one to create rather robust function definitions:

def foo(a, b, c='test', *args, **kwargs):
    ...

a and b are required, c has a default value and is therefore optional, any other positional parameters will be placed into args and any other keyword parameters will be placed into kwargs.

Python also has the ability to specify parameters as keyword-only or positional-only, to add even more specificity using / and *, respectively:

def foo(positional_1, positional_2, /, standard_1, standard_2, *, keyword_1, keyword_2):
    ...

You can read even more about the process at: https://docs.python.org/3/tutorial/controlflow.html#defining-functions

Stephen
  • 1,498
  • 17
  • 26