How to restore package method I overwrote by mistake?

Question:

I overwrote by mistake pyplot.title function with a string, and don’t seem to be able to recover it without restarting the kernel (using Spyder IDE). Is there a way to reload the module?

> import matplotlib.pyplot as plt
> plt.title # plt.title is a function, as expected
<function matplotlib.pyplot.title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)>

My mistake (happens often to me, as I am used to a different language):

> plt.title = 'test'
> plt.title # due to my mistake plt.title is now a string:
'test'

Attempt to reload the module didn’t result in a change in plt.title:

> import matplotlib.pyplot as plt
> plt.title
'test'

Deleting plt seems to remove the package, but after reloading pyplot, the plt.title is still a string:

> del plt
> plt
NameError: name 'plt' is not defined
> plt.title
NameError: name 'plt' is not defined
> import matplotlib.pyplot as plt
> plt.title 
'test'

Can I recover the plt.title function without restarting the kernel?

Asked By: ConfusionWillBeMy

||

Answers:

Try reloading by using importlib.reload.

In [1]: import matplotlib.pyplot as plt                                         

In [2]: plt.title                                                               
Out[2]: <function matplotlib.pyplot.title(label, fontdict=None, loc='center', pad=None, **kwargs)>

In [3]: plt.title = "foo"                                                       

In [4]: plt.title                                                               
Out[4]: 'foo'

In [5]: import importlib                                                        

In [6]: importlib.reload(plt)                                                   
Out[6]: <module 'matplotlib.pyplot' from '/home/ely/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py'>

In [7]: plt.title                                                               
Out[7]: <function matplotlib.pyplot.title(label, fontdict=None, loc='center', pad=None, **kwargs)>
Answered By: ely
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.