Search code examples
pythonshared-librarieslibraries

How to modify the signature of a a function without breaking it in a library


I am building a library that other people in my company are consuming. An example of a function in this library is:

def foo(bar, *baz)

Now, we came up with a new named optional boolean parameter qux that we want to add to foo. I tried to add it at the end:

def foo(bar, *baz, qux=False)

But this will not work as it's an invalid syntax (my IDE even highlights this: regular parameter after * parameter). Adding it before *baz works fine:

def foo(bar, qux=False, *baz)

But this is not backwards compatible, and it will break all the code for every dev that updates this library.

How can I add this new parameter to my function, without breaking all my coworkers apps?

Will all of them need to modify their code to accept this new function?


Solution

  • *baz is a catch-all argument and you can't add a new named argument after that. As a workaround you could do the following:

    def foo(bar, *baz, **kwargs):
        qux = kwargs.get("qux", False)
        # ... rest of your implementation
    

    Granted this won't help your IDE catch errors calling this function, but you won't have to modify it everywhere.