How to hot swap a Python’s function with another using a decorator?

Soufiane Benzaoui
2 min readJun 11, 2020
Hot-swapping functions in Python.

Recently and as a part of a project I was working on, I needed to give the users of my application the ability to use an alternative function in case that the original isn’t working for some reason.

My first hunch was to use a decorator that read the function and swap it with its alternative if it exists in the same module.

So let’s dice in every part of this decorator :

#1

First, the structure of has_alt is the same as any decorator you use typically.
We use @functools.wraps() decorator to update the wrapper function to look like wrapped function by copying attributes such as __name__ and __doc__ .

#2 We use the getmodule method from inspect package to get the name of the module here the function is called . This is important because we don’t want the module of where our function is declared. In the following line, we get an attribute from that module which is in that case is the alternative function. If it can’t be located (because it doesn’t exist for example), it returns a None.

# 3 In order to make this work, our original function needs to have a keyword argument use_alt which is False by default. The decorator will pop it from the keyword arguments list and return the alternative function if it exists (#2). In the all other cases, it returns the original function so our application won’t be interrupted by an unwanted exception.

TEST ! TEST ! TEST !

Let’s see our decorator in action:

In order to demonstrate a use case of the above-created has_alt decorator, We create two functions myfct and the fonction we want it to replace it myfct_alt. The test test_use_raw() will assert that by changing the value of use_alt, the function that will be called is indeed myfct_alt instead of the one that has been called myfct. Thus, the hot swapping works !

Now, we add a new function myfct2 that doesn’t have an alternative, and we create a test to make sure that the no-existence of the alt function won’t cause any problem for our script even that use_alt is set to True.

What Next ?

If you reached that point of the article, you may start wondering if you’ll ever need to use the same decorator in your future development, you’ll probably won’t. That being said, it shows the amazing stuff and workarounds you can do using decorators and little imagination :)

--

--

Soufiane Benzaoui

Python Engineer, VueJs Enthusiastic and a Passionate Indie Hacker!