1 year ago
#77175
user32882
Prevent mocked definition from bleeding over to external library in python
Suppose I have some third-party code main.py
:
import matplotlib.pyplot as plt
import tkinter
tk = tkinter.Tk()
fig = plt.figure()
ax = plt.gca()
ax.plot([1,2,3])
plt.savefig('test.png')
Suppose that, in order to test this code, I need to creat a mock Tk
class and replace the definition in main
with it in a file called mock_main.py
:
import tkinter
class Tk:
pass
tkinter.Tk = Tk
import main
Now, if I run python mock_main.py
, I get an error:
Traceback (most recent call last):
File "C:\Users\user\desktop\temp\compare_mpl_backends\mock_main.py", line 8, in <module>
import main
File "C:\Users\user\desktop\temp\compare_mpl_backends\main.py", line 6, in <module>
fig = plt.figure()
File "C:\Users\user\Miniconda3\envs\temp\lib\site-packages\matplotlib\pyplot.py", line 787, in figure
manager = new_figure_manager(
File "C:\Users\user\Miniconda3\envs\temp\lib\site-packages\matplotlib\pyplot.py", line 306, in new_figure_manager
return _backend_mod.new_figure_manager(*args, **kwargs)
File "C:\Users\user\Miniconda3\envs\temp\lib\site-packages\matplotlib\backend_bases.py", line 3494, in new_figure_manager
return cls.new_figure_manager_given_figure(num, fig)
File "C:\Users\user\Miniconda3\envs\temp\lib\site-packages\matplotlib\backends\_backend_tk.py", line 925, in new_figure_manager_given_figure
window = tk.Tk(className="matplotlib")
TypeError: Tk() takes no arguments
I understand why this error occurs. matplotlib
also depends on tkinter.Tk
, so when I override it in mock_main.py
, it basically breaks the matplotlib
code.
I want to leave matplotlib alone, namely allowing it to use the true definition of Tk
. However, for the third party code main.py
, I want to use my (mock) definition.
Is there any elegant way to achieve this in python without modifying the contents of main.py?
python
matplotlib
tkinter
mocking
monkeypatching
0 Answers
Your Answer