[Small story] A painstaking measure when you have to execute a function before import in Python

It is a small story. It's a rare case, but it's a solution when Python requires you to execute a function or method before importing.

Background

When I installed matplotlib on Linux and used it on my Python code, I got the following error:

_tkinter.TclError: no display name and no $DISPLAY environment variable

The solution to this error comes up as soon as I search, and the answer seems to be that matplotlib's backend should be Agg. (Details about errors and backends are omitted this time)

There seem to be several ways to do this, and the method of writing backend: Agg in / etc / matplotlibrc [^ 1] and the method of usingmatplotlib.use ('Agg')[^ 2] are the top searches. It was up to.

This time, let's assume that we will use matplotlib.use ('Agg').

problem

import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot


def plot(data):
    pyplot.plot(data)

If you call matplotlibu.use ('Agg') after importing as above, it works, but there is a problem with this, a tool that automatically changes the import order ([isort](https: //) pypi.python.org/pypi/isort) etc.) will be rewritten as follows.

import matplotlib
from matplotlib import pyplot

matplotlib.use('Agg')


def plot(data):
    pyplot.plot(data)

It seems that matplotlib.use ('Agg') must be called before writing from matplotlib import pyplot, which can be a problem if CI automatically checks the code. There is a way to import it in the calling function at runtime, but it becomes more complicated as the number of imports and the number of functions increases.

Countermeasures

As a countermeasure, it can be implemented as follows.

try:
    import matplotlib
    matplotlib.use('Agg')
finally:
    from matplotlib import pyplot


def plot(data):
    pyplot.plot(data)

For the time being, this can guarantee the order.

[^ 1]: How to prevent recurrence of matplotlib moss problem with undefined $ DISPLAY

[^ 2]: Draw a graph with matplotlib.

Recommended Posts

[Small story] A painstaking measure when you have to execute a function before import in Python
To execute a Python enumerate function in JavaScript
How to import a file anywhere you like in Python
[Subprocess] When you want to execute another Python program in Python code
Precautions when pickling a function in python
[Python] What to check when you get a Unicode Decode Error in Django
Things to note when initializing a list in Python
Specifies the function to execute when the python program ends
When you want to plt.save in a for statement
How to execute a command using subprocess in Python
Understand Python yield If you put yield in a function, it will change to a generator
[Django] A memorandum when you want to communicate asynchronously [Python3]
[C / C ++] Pass the value calculated in C / C ++ to a python function to execute the process, and use that value in C / C ++.
Create a function in Python
A story about how to specify a relative path in python.
To return char * in a callback function using ctypes in Python
To know which bin a given value goes into when you have a bin delimiter in ndarray
[Python] When you want to import and use your own package in the upper directory
A story about trying to implement a private variable in Python.
When you want to hit a UNIX command on Python
The story I was addicted to when I specified nil as a function argument in Go
Write a script in Shell and Python to notify you in Slack when the process is finished
A story that didn't work when I tried to log in with the Python requests module
When you want to replace multiple characters in a string without using regular expressions in python3 series
What to do if you get a minus zero in Python
[Python] Execution time when a function is entered in a dictionary value
Timezone specification when converting a string to datetime type in python
[Python] When you want to use all variables in another file
I wrote a function to load a Git extension script in Python
If you want to assign csv export to a variable in python
[Python3] Define a decorator to measure the execution time of a function
Check if you can connect to a TCP port in Python
Precautions when giving default values to arguments in Python function definitions
Measure function execution time in Python
When writing a program in Python
[Python] What to do if you get a ModuleNotFoundError when importing pandas using Jupyter Notebook in Anaconda
[Small story] How to save matplotlib graphs in a batch with Jupyter
Have Alexa run Python to give you a sense of the future
Note: [Python3] Convert datetime to a string in any format you like
A story I was addicted to when inserting from Python to a PostgreSQL table
When you make a mistake in the directory where you execute `pipenv install`
How to put a half-width space before letters and numbers in Python.
When you get a cannot assign module before Module.init () call in pytorch
How to write a string when there are multiple lines in python
What happens if you do "import A, B as C" in Python?
Python: I want to measure the processing time of a function neatly
How to get a stacktrace in python
[Python] I want to know the variables in the function when an error occurs!
A confusing story with two ways to implement XGBoost in Python + overall notes
Create a plugin that allows you to search Sublime Text 3 tabs in Python
What to do when a warning appears around Python integration in Neovim's CheckHealth
Output timing is incorrect when standard (error) output is converted to a file in Python
How to solve "attempted relative import beyond top-level package" when importing in Python
How to avoid import errors when running python in Synology DSM Task Scheduler
A story that I was addicted to when I made SFTP communication with python
I didn't have to write a decorator in the class Thank you contextmanager
A convenient function memo to use when you want to enter the debugger if an error occurs when running a Python script.
Draw a graph of a quadratic function in Python
Try to calculate a statistical problem in Python
Automatically register function arguments to argparse in Python
How to clear tuples in a list (Python)