• +43 660 1453541
  • contact@germaniumhq.com

Force Named Argument Calling in Python


Force Named Argument Calling in Python

When calling functions in python, it makes sense to name the arguments, since they convey what values mean. A call to update(3, 5) is communicating less than update(major_version=3, minor_version=5). So how do we enforce that?

Let’s assume we have a function declared as:

def update(major_version, minor_version): ...

That means that our users are able to call our function any way they want, as long as they fill in the required parameters.

update(3, 5)  # ok
update(3, minor_version=5)  # also ok
update(major_version=3, minor_version=5)  # ok
update(minor_version=5, major_version=3)  # also ok (1)
  1. Even if in the last sample the parameter order was changed, since all our required parameters are being passed, it’s still ok to call it.

To enforce always passing the parameters we’ll do two things:

  1. capture all the unnamed positional arguments

  2. fail if any positional argument is passed

Thus our definition becomes:

def update(*args, major_version, minor_version):  # (1)
    if args:  # (2)
        raise Exception("You need to use argument names")

    # original code

The major_version, and minor_version are still required parameters, but now the only way to set them is via name assignment in the function call:

update(3, 5)                              # exception
update(3, minor_version=5)                # exception
update(minor_version=5)                   # exception
update(major_version=3, minor_version=5)  # ok
update(minor_version=5, major_version=3)  # ok

This enforces clarity in the calls, where no more magic numbers and strings are being passed around.