From 7ac315eac1f23cd991f13e3a4173c6f467e1b041 Mon Sep 17 00:00:00 2001 From: Oscar Gustafsson Date: Sat, 15 Oct 2022 16:35:24 +0200 Subject: [PATCH] Backport PR #24178: Fall back to Python-level Thread for GUI warning --- lib/matplotlib/pyplot.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index e5ae9a0cc11c..6f757ae031ef 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -332,11 +332,21 @@ def draw_if_interactive(): def _warn_if_gui_out_of_main_thread(): - # This compares native thread ids because even if python-level Thread - # objects match, the underlying OS thread (which is what really matters) - # may be different on Python implementations with green threads. - if (_get_required_interactive_framework(_get_backend_mod()) and - threading.get_native_id() != threading.main_thread().native_id): + warn = False + if _get_required_interactive_framework(_get_backend_mod()): + if hasattr(threading, 'get_native_id'): + # This compares native thread ids because even if Python-level + # Thread objects match, the underlying OS thread (which is what + # really matters) may be different on Python implementations with + # green threads. + if threading.get_native_id() != threading.main_thread().native_id: + warn = True + else: + # Fall back to Python-level Thread if native IDs are unavailable, + # mainly for PyPy. + if threading.current_thread() is not threading.main_thread(): + warn = True + if warn: _api.warn_external( "Starting a Matplotlib GUI outside of the main thread will likely " "fail.")