How do I reload a Python library?

In the above post, we discussed that accidentally assigning values to built-in function can generate errors like TypeError: 'float' object is not callable. And the solution was to delete the redefined function using del keyword (for example: del float). What happens here is that it restores the function definition of float function after deleting the value assigned to it. This works well for built-in functions.

However, what if we accidentally redefined a library’s function? For example, what if we try to do this:

import matplotlib.pyplot as plt
plt.xlabel = "Hello World"
plt.xlabel("Hello World")

TypeErrorTraceback (most recent call last)
<ipython-input-1-cbdd8381e5c5> in <module>()
----> 1 plt.xlabel("Hello World")

TypeError: 'str' object is not callable

We cannot do del plt.xlabel because it will delete, but will not restore the function definition of plt.xlabel(). Luckily, there is a way to reload a Python library. And here is how to do it.

from importlib import reload
plt.xlabel("Hello World")

Here, we are importing the reload() function from importlib module. Then calling the reload() function with plt as argument. This will reload all the functions and variables in the matplotlib.pyplot (plt) module. And thus, plt.xlabel()'s function definition will be restored.

A friendly tip
Don’t redefine the reload() function :wink: