Repository: joblib/loky (language: python)

Issue:
MAINT introduce black to loky
Introducing black with 79 characters.


Discussion / hints:
I would prefer to use black with the default parametrization (88) to stay consistent with other projects' conventions.
> I would prefer to use black with the default parametrization (88) to stay consistent with other projects' conventions.

I think @tomMoral expressed strong disagreement :)
Community-wide consistency beats @tomMoral's  aesthetic preferences in my opinion :)
When introducing the changes, I think that we need to do particular attention to string concatenation then.
> Community-wide consistency beats @tomMoral's  aesthetic preferences in my opinion :)

consistency with cpython seems more important than uniformization 😅
As you wish. I won't fight for 88. But the standard library of cpython is not even self-consistent from a coding style point of view so I wouldn't use it as a reference.
We have `ERROR at teardown of TestsProcessPoolForkserverExecutor.test_map_exception` (timeout then stalled build) in `test_loky linux-python-py38-high-memory`. 

This might be the same problem as reported in #328 although in the teardown of a different test (`TestsProcessPoolForkserverExecutor.test_map_chunksize`).

I will cancel the this build on Azure.
I am fine if we use the `88`.

If it is the norm with `black`, let's avoid having more  special cases.
My main issue with this change is that it will be inconsistent with all the other projects I am involved with.
But if I am the only one, I can live with this

I think we should also add a flake8 check because black does not catch unused imports for instance

Fix patch:
diff --git a/.azure_pipeline.yml b/.azure_pipeline.yml
index 61194faf..47178e46 100644
--- a/.azure_pipeline.yml
+++ b/.azure_pipeline.yml
@@ -1,4 +1,20 @@
 jobs:
+- job: linting
+  displayName: Linting
+  pool:
+    vmImage: ubuntu-20.04
+  steps:
+    - task: UsePythonVersion@0
+      inputs:
+        versionSpec: '3.9'
+    - bash: |
+        # Include pytest compatibility with mypy
+        pip install black==22.3
+      displayName: Install linters
+    - bash: |
+        black --check --diff .
+      displayName: Run black
+
 - job: 'test_loky'
   strategy:
     matrix:
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 00000000..a7a6bc6d
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,11 @@
+repos:
+-   repo: https://github.com/pre-commit/pre-commit-hooks
+    rev: v4.3.0
+    hooks:
+    -   id: check-yaml
+    -   id: end-of-file-fixer
+    -   id: trailing-whitespace
+-   repo: https://github.com/psf/black
+    rev: 22.3.0
+    hooks:
+    -   id: black
diff --git a/continuous_integration/install_coverage_subprocess_pth.py b/continuous_integration/install_coverage_subprocess_pth.py
index 2cf32c6b..578286e0 100644
--- a/continuous_integration/install_coverage_subprocess_pth.py
+++ b/continuous_integration/install_coverage_subprocess_pth.py
@@ -9,8 +9,8 @@
 import coverage; coverage.process_startup()
 """
 
-filename = op.join(get_python_lib(), 'coverage_subprocess.pth')
-with open(filename, mode='w') as f:
+filename = op.join(get_python_lib(), "coverage_subprocess.pth")
+with open(filename, mode="w") as f:
     f.write(FILE_CONTENT)
 
-print(f'Installed subprocess coverage support: {filename}')
+print(f"Installed subprocess coverage support: {filename}")
diff --git a/docs/conf.py b/docs/conf.py
index cba4b923..3910f0ef 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -20,7 +20,7 @@
 import os
 import sys
 
-sys.path.insert(0, os.path.abspath('../loky'))
+sys.path.insert(0, os.path.abspath("../loky"))
 
 
 # -- General configuration ------------------------------------------------
@@ -33,30 +33,30 @@
 # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
 # ones.
 extensions = [
-    'sphinx.ext.todo',
-    'sphinx.ext.autodoc',
-    'sphinx.ext.viewcode',
-    'sphinx.ext.autosummary',
-    'sphinx.ext.intersphinx',
-    'sphinx_gallery.gen_gallery'
+    "sphinx.ext.todo",
+    "sphinx.ext.autodoc",
+    "sphinx.ext.viewcode",
+    "sphinx.ext.autosummary",
+    "sphinx.ext.intersphinx",
+    "sphinx_gallery.gen_gallery",
 ]
 
 # Add any paths that contain templates here, relative to this directory.
-templates_path = ['_templates']
+templates_path = ["_templates"]
 
 # The suffix(es) of source filenames.
 # You can specify multiple suffix as a list of string:
 #
 # source_suffix = ['.rst', '.md']
-source_suffix = '.rst'
+source_suffix = ".rst"
 
 # The master toctree document.
-master_doc = 'index'
+master_doc = "index"
 
 # General information about the project.
-project = 'loky'
-copyright = '2017, Thomas Moreau & Olivier Grisel'
-author = 'Thomas Moreau & Olivier Grisel'
+project = "loky"
+copyright = "2017, Thomas Moreau & Olivier Grisel"
+author = "Thomas Moreau & Olivier Grisel"
 
 # The version info for the project you're documenting, acts as replacement for
 # |version| and |release|, also used in various other places throughout the
@@ -64,6 +64,7 @@
 #
 # The short X.Y version.
 from loky import __version__ as version  # noqa
+
 # The full version, including alpha/beta/rc tags.
 release = version
 
@@ -77,10 +78,10 @@
 # List of patterns, relative to source directory, that match files and
 # directories to ignore when looking for source files.
 # This patterns also effect to html_static_path and html_extra_path
-exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
+exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
 
 # The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'sphinx'
+pygments_style = "sphinx"
 
 # If true, `todo` and `todoList` produce output, else they produce nothing.
 todo_include_todos = True
@@ -90,13 +91,13 @@
 
 # The theme to use for HTML and HTML Help pages.  See the documentation for
 # a list of builtin themes.
-html_theme = 'alabaster'
+html_theme = "alabaster"
 
 # Theme options are theme-specific and customize the look and feel of a theme
 # further.  For a list of options available for each theme, see the
 # documentation.
 html_theme_options = {
-    'navbar_sidebarrel': False,
+    "navbar_sidebarrel": False,
 }
 # Theme options are theme-specific and customize the look and feel of a theme
 # further.  For a list of options available for each theme, see the
@@ -107,7 +108,7 @@
 # Add any paths that contain custom static files (such as style sheets) here,
 # relative to this directory. They are copied after the builtin static files,
 # so a file named "default.css" will overwrite the builtin "default.css".
-html_static_path = ['_static']
+html_static_path = ["_static"]
 
 # Custom sidebar templates, must be a dictionary that maps document names
 # to template names.
@@ -128,7 +129,7 @@
 # -- Options for HTMLHelp output ------------------------------------------
 
 # Output file base name for HTML help builder.
-htmlhelp_basename = 'lokydoc'
+htmlhelp_basename = "lokydoc"
 
 
 # -- Options for LaTeX output ---------------------------------------------
@@ -137,15 +138,12 @@
     # The paper size ('letterpaper' or 'a4paper').
     #
     # 'papersize': 'letterpaper',
-
     # The font size ('10pt', '11pt' or '12pt').
     #
     # 'pointsize': '10pt',
-
     # Additional stuff for the LaTeX preamble.
     #
     # 'preamble': '',
-
     # Latex figure (float) alignment
     #
     # 'figure_align': 'htbp',
@@ -155,8 +153,13 @@
 # (source start file, target name, title,
 #  author, documentclass [howto, manual, or own class]).
 latex_documents = [
-    (master_doc, 'loky.tex', 'loky Documentation',
-     'Thomas Moreau \\& Olivier Grisel', 'manual'),
+    (
+        master_doc,
+        "loky.tex",
+        "loky Documentation",
+        "Thomas Moreau \\& Olivier Grisel",
+        "manual",
+    ),
 ]
 
 
@@ -164,10 +167,7 @@
 
 # One entry per manual page. List of tuples
 # (source start file, name, description, authors, manual section).
-man_pages = [
-    (master_doc, 'loky', 'loky Documentation',
-     [author], 1)
-]
+man_pages = [(master_doc, "loky", "loky Documentation", [author], 1)]
 
 
 # -- Options for Texinfo output -------------------------------------------
@@ -176,30 +176,32 @@
 # (source start file, target name, title, author,
 #  dir menu entry, description, category)
 texinfo_documents = [
-    (master_doc, 'loky', 'loky Documentation',
-     author, 'loky', 'One line description of project.',
-     'Miscellaneous'),
+    (
+        master_doc,
+        "loky",
+        "loky Documentation",
+        author,
+        "loky",
+        "One line description of project.",
+        "Miscellaneous",
+    ),
 ]
 
 
 sphinx_gallery_conf = {
     # path to your examples scripts
-    'examples_dirs': '../examples',
+    "examples_dirs": "../examples",
     # path where to save gallery generated examples
-    'gallery_dirs': 'auto_examples',
-    'filename_pattern': '',
-    'ignore_pattern': 'deadlock_',
-    'reference_url': {
-        'loky': None
-    },
-    'default_thumb_file': '_static/loky_logo.png',
-
+    "gallery_dirs": "auto_examples",
+    "filename_pattern": "",
+    "ignore_pattern": "deadlock_",
+    "reference_url": {"loky": None},
+    "default_thumb_file": "_static/loky_logo.png",
     # directory where function granular galleries are stored
-    'backreferences_dir': 'gen_modules/backreferences',
-
+    "backreferences_dir": "gen_modules/backreferences",
     # Modules for which function level galleries are created.  In
     # this case sphinx_gallery and numpy in a tuple of strings.
-    'doc_module': ('loky')
+    "doc_module": ("loky"),
 }
 
-intersphinx_mapping = {'python': ('https://docs.python.org/3', None)}
+intersphinx_mapping = {"python": ("https://docs.python.org/3", None)}
diff --git a/examples/cloudpickle_wrapper.py b/examples/cloudpickle_wrapper.py
index d784e7e0..5d323cb2 100644
--- a/examples/cloudpickle_wrapper.py
+++ b/examples/cloudpickle_wrapper.py
@@ -66,7 +66,7 @@ def func_async(i, *args):
 # Now set the `loky_pickler` to use the pickle serialization from stdlib. Here,
 # we do not pass the desired function ``call_function`` as it is not picklable
 # but it is replaced by ``id`` for demonstration purposes.
-set_loky_pickler('pickle')
+set_loky_pickler("pickle")
 t_start = time.time()
 executor = get_reusable_executor(max_workers=1)
 executor.submit(id, large_list).result()
@@ -97,6 +97,7 @@ def func_async(i, *args):
 # instances.
 #
 
+
 @wrap_non_picklable_objects
 def func_async_wrapped(i, *args):
     return 2 * i
diff --git a/examples/deadlocks/deadlock_on_failed_pickle.py b/examples/deadlocks/deadlock_on_failed_pickle.py
index d338bb0e..65df2c39 100644
--- a/examples/deadlocks/deadlock_on_failed_pickle.py
+++ b/examples/deadlocks/deadlock_on_failed_pickle.py
@@ -18,9 +18,11 @@ def __reduce__(self):
 
 if __name__ == "__main__":
     parser = argparse.ArgumentParser()
-    parser.add_argument('--use-stdlib', action="store_true",
-                        help='Use concurrent.futures.ProcessPoolExecutor'
-                             ' instead of loy')
+    parser.add_argument(
+        "--use-stdlib",
+        action="store_true",
+        help="Use concurrent.futures.ProcessPoolExecutor" " instead of loy",
+    )
     args = parser.parse_args()
     if args.use_stdlib:
         from concurrent.futures import ProcessPoolExecutor
diff --git a/examples/deadlocks/deadlock_on_shutdown.py b/examples/deadlocks/deadlock_on_shutdown.py
index 8aecb777..2d3e95cd 100644
--- a/examples/deadlocks/deadlock_on_shutdown.py
+++ b/examples/deadlocks/deadlock_on_shutdown.py
@@ -18,9 +18,11 @@ def __reduce__(self):
 
 if __name__ == "__main__":
     parser = argparse.ArgumentParser()
-    parser.add_argument('--use-stdlib', action="store_true",
-                        help='Use concurrent.futures.ProcessPoolExecutor'
-                             ' instead of loky')
+    parser.add_argument(
+        "--use-stdlib",
+        action="store_true",
+        help="Use concurrent.futures.ProcessPoolExecutor" " instead of loky",
+    )
     args = parser.parse_args()
     if args.use_stdlib:
         from concurrent.futures import ProcessPoolExecutor
diff --git a/examples/deadlocks/deadlock_results.py b/examples/deadlocks/deadlock_results.py
index b9195480..6622a69f 100644
--- a/examples/deadlocks/deadlock_results.py
+++ b/examples/deadlocks/deadlock_results.py
@@ -23,14 +23,16 @@ class ObjectWithPickleError:
     """Triggers a RuntimeError when sending job to the workers"""
 
     def __reduce__(self):
-        return raise_error, (UnpicklingError, )
+        return raise_error, (UnpicklingError,)
 
 
 if __name__ == "__main__":
     parser = argparse.ArgumentParser()
-    parser.add_argument('--use-stdlib', action="store_true",
-                        help='Use concurrent.futures.ProcessPoolExecutor'
-                             ' instead of loky')
+    parser.add_argument(
+        "--use-stdlib",
+        action="store_true",
+        help="Use concurrent.futures.ProcessPoolExecutor" " instead of loky",
+    )
     args = parser.parse_args()
     if args.use_stdlib:
         from concurrent.futures import ProcessPoolExecutor
diff --git a/examples/deadlocks/deadlock_timeout_shutdown.py b/examples/deadlocks/deadlock_timeout_shutdown.py
index ba5a7e05..2aa4fc6d 100644
--- a/examples/deadlocks/deadlock_timeout_shutdown.py
+++ b/examples/deadlocks/deadlock_timeout_shutdown.py
@@ -13,7 +13,7 @@
 
 
 class SlowPickle:
-    def __init__(self, delay=.1):
+    def __init__(self, delay=0.1):
         self.delay = delay
 
     def __reduce__(self):
@@ -24,6 +24,6 @@ def __reduce__(self):
 if __name__ == "__main__":
     ctx = get_context("spawn")
     o = SlowPickle()
-    with ProcessPoolExecutor(max_workers=2, timeout=.01, context=ctx) as e:
+    with ProcessPoolExecutor(max_workers=2, timeout=0.01, context=ctx) as e:
         f = e.submit(id, SlowPickle())
     f.result()
diff --git a/examples/reuse_executor.py b/examples/reuse_executor.py
index 97391772..50f65b1a 100644
--- a/examples/reuse_executor.py
+++ b/examples/reuse_executor.py
@@ -46,5 +46,7 @@ def test_3():
 print("All the jobs were run in a process different from main process")
 
 assert len(set(pids)) == 1
-print("All the computation where run in a single `ProcessPoolExecutor` with "
-      f"worker pid={pids[0]}")
+print(
+    "All the computation where run in a single `ProcessPoolExecutor` with "
+    f"worker pid={pids[0]}"
+)
diff --git a/examples/reuseable_executor.py b/examples/reuseable_executor.py
index 9d8c5b9c..bd3cc0c3 100644
--- a/examples/reuseable_executor.py
+++ b/examples/reuseable_executor.py
@@ -23,24 +23,28 @@ def initializer(x):
 def return_initializer_status(delay=0):
     sleep(delay)
 
-    return getattr(loky, '_INITIALIZER_STATUS', 'uninitialized')
+    return getattr(loky, "_INITIALIZER_STATUS", "uninitialized")
 
 
 executor = get_reusable_executor(
-    max_workers=2, initializer=initializer, initargs=('initialized',),
-    context="loky", timeout=1000)
+    max_workers=2,
+    initializer=initializer,
+    initargs=("initialized",),
+    context="loky",
+    timeout=1000,
+)
 
 assert loky._INITIALIZER_STATUS == "uninitialized"
 executor.submit(return_initializer_status).result()
-assert executor.submit(return_initializer_status).result() == 'initialized'
+assert executor.submit(return_initializer_status).result() == "initialized"
 
 # With reuse=True, the executor use the same initializer
 executor = get_reusable_executor(max_workers=4, reuse=True)
-for x in executor.map(return_initializer_status, [.5] * 4):
-    assert x == 'initialized'
+for x in executor.map(return_initializer_status, [0.5] * 4):
+    assert x == "initialized"
 
 # With reuse='auto', the initializer is not used anymore as a new executor
 # is created.
 executor = get_reusable_executor(max_workers=4)
-for x in executor.map(return_initializer_status, [.1] * 4):
-    assert x == 'uninitialized'
+for x in executor.map(return_initializer_status, [0.1] * 4):
+    assert x == "uninitialized"
diff --git a/loky/__init__.py b/loky/__init__.py
index e9fc121f..2d5c0810 100644
--- a/loky/__init__.py
+++ b/loky/__init__.py
@@ -22,11 +22,23 @@
 from .process_executor import BrokenProcessPool, ProcessPoolExecutor
 
 
-__all__ = ["get_reusable_executor", "cpu_count", "wait", "as_completed",
-           "Future", "Executor", "ProcessPoolExecutor",
-           "BrokenProcessPool", "CancelledError", "TimeoutError",
-           "FIRST_COMPLETED", "FIRST_EXCEPTION", "ALL_COMPLETED",
-           "wrap_non_picklable_objects", "set_loky_pickler"]
+__all__ = [
+    "get_reusable_executor",
+    "cpu_count",
+    "wait",
+    "as_completed",
+    "Future",
+    "Executor",
+    "ProcessPoolExecutor",
+    "BrokenProcessPool",
+    "CancelledError",
+    "TimeoutError",
+    "FIRST_COMPLETED",
+    "FIRST_EXCEPTION",
+    "ALL_COMPLETED",
+    "wrap_non_picklable_objects",
+    "set_loky_pickler",
+]
 
 
-__version__ = '3.4.0.dev0'
+__version__ = "3.4.0.dev0"
diff --git a/loky/_base.py b/loky/_base.py
index cd8f3410..da0abc1e 100644
--- a/loky/_base.py
+++ b/loky/_base.py
@@ -25,4 +25,4 @@ def _invoke_callbacks(self):
             try:
                 callback(self)
             except BaseException:
-                LOGGER.exception(f'exception calling callback for {self!r}')
+                LOGGER.exception(f"exception calling callback for {self!r}")
diff --git a/loky/backend/__init__.py b/loky/backend/__init__.py
index c31023cc..d339aa64 100644
--- a/loky/backend/__init__.py
+++ b/loky/backend/__init__.py
@@ -5,7 +5,7 @@
 
 
 def _make_name():
-    return f'/loky-{os.getpid()}-{next(synchronize.SemLock._rand)}'
+    return f"/loky-{os.getpid()}-{next(synchronize.SemLock._rand)}"
 
 
 # monkey patch the name creation for multiprocessing
diff --git a/loky/backend/_posix_reduction.py b/loky/backend/_posix_reduction.py
index e9f34ed5..4b800ec0 100644
--- a/loky/backend/_posix_reduction.py
+++ b/loky/backend/_posix_reduction.py
@@ -14,9 +14,11 @@
 
 from .reduction import register
 
-HAVE_SEND_HANDLE = (hasattr(socket, 'CMSG_LEN') and
-                    hasattr(socket, 'SCM_RIGHTS') and
-                    hasattr(socket.socket, 'sendmsg'))
+HAVE_SEND_HANDLE = (
+    hasattr(socket, "CMSG_LEN")
+    and hasattr(socket, "SCM_RIGHTS")
+    and hasattr(socket.socket, "sendmsg")
+)
 
 
 def _mk_inheritable(fd):
@@ -25,17 +27,18 @@ def _mk_inheritable(fd):
 
 
 def DupFd(fd):
-    '''Return a wrapper for an fd.'''
+    """Return a wrapper for an fd."""
     popen_obj = get_spawning_popen()
     if popen_obj is not None:
         return popen_obj.DupFd(popen_obj.duplicate_for_child(fd))
     elif HAVE_SEND_HANDLE:
         from multiprocessing import resource_sharer
+
         return resource_sharer.DupFd(fd)
     else:
         raise TypeError(
-            'Cannot pickle connection object. This object can only be '
-            'passed when spawning a new process'
+            "Cannot pickle connection object. This object can only be "
+            "passed when spawning a new process"
         )
 
 
diff --git a/loky/backend/_win_reduction.py b/loky/backend/_win_reduction.py
index 7f50c9f6..99fcb78c 100644
--- a/loky/backend/_win_reduction.py
+++ b/loky/backend/_win_reduction.py
@@ -23,8 +23,8 @@ def __init__(self, handle, access, pid=None):
         proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False, pid)
         try:
             self._handle = _winapi.DuplicateHandle(
-                _winapi.GetCurrentProcess(),
-                handle, proc, access, False, 0)
+                _winapi.GetCurrentProcess(), handle, proc, access, False, 0
+            )
         finally:
             _winapi.CloseHandle(proc)
         self._access = access
@@ -34,12 +34,18 @@ def detach(self):
         # retrieve handle from process which currently owns it
         if self._pid == os.getpid():
             return self._handle
-        proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False,
-                                   self._pid)
+        proc = _winapi.OpenProcess(
+            _winapi.PROCESS_DUP_HANDLE, False, self._pid
+        )
         try:
             return _winapi.DuplicateHandle(
-                proc, self._handle, _winapi.GetCurrentProcess(),
-                self._access, False, _winapi.DUPLICATE_CLOSE_SOURCE)
+                proc,
+                self._handle,
+                _winapi.GetCurrentProcess(),
+                self._access,
+                False,
+                _winapi.DUPLICATE_CLOSE_SOURCE,
+            )
         finally:
             _winapi.CloseHandle(proc)
 
@@ -50,8 +56,9 @@ def rebuild_pipe_connection(dh, readable, writable):
 
 
 def reduce_pipe_connection(conn):
-    access = ((_winapi.FILE_GENERIC_READ if conn.readable else 0) |
-              (_winapi.FILE_GENERIC_WRITE if conn.writable else 0))
+    access = (_winapi.FILE_GENERIC_READ if conn.readable else 0) | (
+        _winapi.FILE_GENERIC_WRITE if conn.writable else 0
+    )
     dh = DupHandle(conn.fileno(), access)
     return rebuild_pipe_connection, (dh, conn.readable, conn.writable)
 
diff --git a/loky/backend/context.py b/loky/backend/context.py
index a8c74446..af7be78a 100644
--- a/loky/backend/context.py
+++ b/loky/backend/context.py
@@ -21,9 +21,9 @@
 
 from .process import LokyProcess, LokyInitMainProcess
 
-START_METHODS = ['loky', 'loky_init_main', 'spawn']
-if sys.platform != 'win32':
-    START_METHODS += ['fork', 'forkserver']
+START_METHODS = ["loky", "loky_init_main", "spawn"]
+if sys.platform != "win32":
+    START_METHODS += ["fork", "forkserver"]
 
 _DEFAULT_START_METHOD = None
 
@@ -37,9 +37,12 @@ def get_context(method=None):
     method = method or _DEFAULT_START_METHOD or "loky"
     if method == "fork":
         # If 'fork' is explicitly requested, warn user about potential issues.
-        warnings.warn("`fork` start method should not be used with "
-                      "`loky` as it does not respect POSIX. Try using "
-                      "`spawn` or `loky` instead.", UserWarning)
+        warnings.warn(
+            "`fork` start method should not be used with "
+            "`loky` as it does not respect POSIX. Try using "
+            "`spawn` or `loky` instead.",
+            UserWarning,
+        )
     try:
         return mp_get_context(method)
     except ValueError:
@@ -52,7 +55,7 @@ def get_context(method=None):
 def set_start_method(method, force=False):
     global _DEFAULT_START_METHOD
     if _DEFAULT_START_METHOD is not None and not force:
-        raise RuntimeError('context has already been set')
+        raise RuntimeError("context has already been set")
     assert method is None or method in START_METHODS, (
         f"'{method}' is not a valid start_method. It should be in "
         f"{START_METHODS}"
@@ -112,7 +115,8 @@ def cpu_count(only_physical_cores=False):
             f"following reason:\n{exception}\n"
             "Returning the number of logical cores instead. You can "
             "silence this warning by setting LOKY_MAX_CPU_COUNT to "
-            "the number of cores you want to use.")
+            "the number of cores you want to use."
+        )
         traceback.print_tb(exception.__traceback__)
 
     return aggregate_cpu_count
@@ -156,7 +160,7 @@ def _cpu_count_cgroup(os_cpu_count):
 
 def _cpu_count_affinity(os_cpu_count):
     # Number of available CPUs given affinity settings
-    if hasattr(os, 'sched_getaffinity'):
+    if hasattr(os, "sched_getaffinity"):
         try:
             return len(os.sched_getaffinity(0))
         except NotImplementedError:
@@ -174,7 +178,7 @@ def _cpu_count_affinity(os_cpu_count):
     except ImportError:  # pragma: no cover
         if (
             sys.platform == "linux"
-            and os.environ.get('LOKY_MAX_CPU_COUNT') is None
+            and os.environ.get("LOKY_MAX_CPU_COUNT") is None
         ):
             # PyPy does not implement os.sched_getaffinity on Linux which
             # can cause severe oversubscription problems. Better warn the
@@ -197,7 +201,7 @@ def _cpu_count_user(os_cpu_count):
     cpu_count_cgroup = _cpu_count_cgroup(os_cpu_count)
 
     # User defined soft-limit passed as a loky specific environment variable.
-    cpu_count_loky = int(os.environ.get('LOKY_MAX_CPU_COUNT', os_cpu_count))
+    cpu_count_loky = int(os.environ.get("LOKY_MAX_CPU_COUNT", os_cpu_count))
 
     return min(cpu_count_affinity, cpu_count_cgroup, cpu_count_loky)
 
@@ -221,22 +225,30 @@ def _count_physical_cores():
     try:
         if sys.platform == "linux":
             cpu_info = subprocess.run(
-                "lscpu --parse=core".split(), capture_output=True, text=True)
+                "lscpu --parse=core".split(), capture_output=True, text=True
+            )
             cpu_info = cpu_info.stdout.splitlines()
             cpu_info = {line for line in cpu_info if not line.startswith("#")}
             cpu_count_physical = len(cpu_info)
         elif sys.platform == "win32":
             cpu_info = subprocess.run(
                 "wmic CPU Get NumberOfCores /Format:csv".split(),
-                capture_output=True, text=True)
+                capture_output=True,
+                text=True,
+            )
             cpu_info = cpu_info.stdout.splitlines()
-            cpu_info = [l.split(",")[1] for l in cpu_info
-                        if (l and l != "Node,NumberOfCores")]
+            cpu_info = [
+                l.split(",")[1]
+                for l in cpu_info
+                if (l and l != "Node,NumberOfCores")
+            ]
             cpu_count_physical = sum(map(int, cpu_info))
         elif sys.platform == "darwin":
             cpu_info = subprocess.run(
                 "sysctl -n hw.physicalcpu".split(),
-                capture_output=True, text=True)
+                capture_output=True,
+                text=True,
+            )
             cpu_info = cpu_info.stdout
             cpu_count_physical = int(cpu_info)
         else:
@@ -244,8 +256,7 @@ def _count_physical_cores():
 
         # if cpu_count_physical < 1, we did not find a valid value
         if cpu_count_physical < 1:
-            raise ValueError(
-                f"found {cpu_count_physical} physical cores < 1")
+            raise ValueError(f"found {cpu_count_physical} physical cores < 1")
 
     except Exception as e:
         exception = e
@@ -259,19 +270,21 @@ def _count_physical_cores():
 
 class LokyContext(BaseContext):
     """Context relying on the LokyProcess."""
-    _name = 'loky'
+
+    _name = "loky"
     Process = LokyProcess
     cpu_count = staticmethod(cpu_count)
 
     def Queue(self, maxsize=0, reducers=None):
-        '''Returns a queue object'''
+        """Returns a queue object"""
         from .queues import Queue
-        return Queue(maxsize, reducers=reducers,
-                     ctx=self.get_context())
+
+        return Queue(maxsize, reducers=reducers, ctx=self.get_context())
 
     def SimpleQueue(self, reducers=None):
-        '''Returns a queue object'''
+        """Returns a queue object"""
         from .queues import SimpleQueue
+
         return SimpleQueue(reducers=reducers, ctx=self.get_context())
 
     if sys.platform != "win32":
@@ -279,34 +292,41 @@ def SimpleQueue(self, reducers=None):
         ensuring that we use the loky.backend.resource_tracker to clean-up
         the semaphores in case of a worker crash.
         """
+
         def Semaphore(self, value=1):
             """Returns a semaphore object"""
             from .synchronize import Semaphore
+
             return Semaphore(value=value)
 
         def BoundedSemaphore(self, value):
             """Returns a bounded semaphore object"""
             from .synchronize import BoundedSemaphore
+
             return BoundedSemaphore(value)
 
         def Lock(self):
             """Returns a lock object"""
             from .synchronize import Lock
+
             return Lock()
 
         def RLock(self):
             """Returns a recurrent lock object"""
             from .synchronize import RLock
+
             return RLock()
 
         def Condition(self, lock=None):
             """Returns a condition object"""
             from .synchronize import Condition
+
             return Condition(lock)
 
         def Event(self):
             """Returns an event object"""
             from .synchronize import Event
+
             return Event()
 
 
@@ -324,11 +344,12 @@ class LokyInitMainContext(LokyContext):
     For more details, see the end of the following section of python doc
     https://docs.python.org/3/library/multiprocessing.html#multiprocessing-programming
     """
-    _name = 'loky_init_main'
+
+    _name = "loky_init_main"
     Process = LokyInitMainProcess
 
 
 # Register loky context so it works with multiprocessing.get_context
 ctx_loky = LokyContext()
-mp.context._concrete_contexts['loky'] = ctx_loky
-mp.context._concrete_contexts['loky_init_main'] = LokyInitMainContext()
+mp.context._concrete_contexts["loky"] = ctx_loky
+mp.context._concrete_contexts["loky_init_main"] = LokyInitMainContext()
diff --git a/loky/backend/fork_exec.py b/loky/backend/fork_exec.py
index 211d1835..2353c42f 100644
--- a/loky/backend/fork_exec.py
+++ b/loky/backend/fork_exec.py
@@ -16,9 +16,10 @@ def close_fds(keep_fds):  # pragma: no cover
 
     # We try to retrieve all the open fds
     try:
-        open_fds = {int(fd) for fd in os.listdir('/proc/self/fd')}
+        open_fds = {int(fd) for fd in os.listdir("/proc/self/fd")}
     except FileNotFoundError:
         import resource
+
         max_nfds = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
         open_fds = {*range(max_nfds)}
 
diff --git a/loky/backend/popen_loky_posix.py b/loky/backend/popen_loky_posix.py
index 37a73172..74395be0 100644
--- a/loky/backend/popen_loky_posix.py
+++ b/loky/backend/popen_loky_posix.py
@@ -15,13 +15,14 @@
 from . import reduction, resource_tracker, spawn
 
 
-__all__ = ['Popen']
+__all__ = ["Popen"]
 
 
 #
 # Wrapper for an fd used while launching a process
 #
 
+
 class _DupFd:
     def __init__(self, fd):
         self.fd = reduction._mk_inheritable(fd)
@@ -34,8 +35,9 @@ def detach(self):
 # Start child process using subprocess.Popen
 #
 
+
 class Popen:
-    method = 'loky'
+    method = "loky"
     DupFd = _DupFd
 
     def __init__(self, process_obj):
@@ -96,7 +98,8 @@ def _launch(self, process_obj):
         try:
             prep_data = spawn.get_preparation_data(
                 process_obj._name,
-                getattr(process_obj, "init_main_module", True))
+                getattr(process_obj, "init_main_module", True),
+            )
             reduction.dump(prep_data, fp)
             reduction.dump(process_obj, fp)
 
@@ -110,27 +113,28 @@ def _launch(self, process_obj):
             #     _mk_inheritable(fd)
 
             cmd_python = [sys.executable]
-            cmd_python += ['-m', self.__module__]
-            cmd_python += ['--process-name', str(process_obj.name)]
-            cmd_python += ['--pipe', str(reduction._mk_inheritable(child_r))]
+            cmd_python += ["-m", self.__module__]
+            cmd_python += ["--process-name", str(process_obj.name)]
+            cmd_python += ["--pipe", str(reduction._mk_inheritable(child_r))]
             reduction._mk_inheritable(child_w)
             reduction._mk_inheritable(tracker_fd)
             self._fds += [child_r, child_w, tracker_fd]
-            if sys.version_info >= (3, 8) and os.name == 'posix':
-                mp_tracker_fd = prep_data['mp_tracker_args']['fd']
+            if sys.version_info >= (3, 8) and os.name == "posix":
+                mp_tracker_fd = prep_data["mp_tracker_args"]["fd"]
                 self.duplicate_for_child(mp_tracker_fd)
 
             from .fork_exec import fork_exec
+
             pid = fork_exec(cmd_python, self._fds, env=process_obj.env)
             util.debug(
                 f"launched python with pid {pid} and cmd:\n{cmd_python}"
             )
             self.sentinel = parent_r
 
-            method = 'getbuffer'
+            method = "getbuffer"
             if not hasattr(fp, method):
-                method = 'getvalue'
-            with os.fdopen(parent_w, 'wb') as f:
+                method = "getvalue"
+            with os.fdopen(parent_w, "wb") as f:
                 f.write(getattr(fp, method)())
             self.pid = pid
         finally:
@@ -145,20 +149,26 @@ def thread_is_spawning():
         return True
 
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     import argparse
-    parser = argparse.ArgumentParser('Command line parser')
-    parser.add_argument('--pipe', type=int, required=True,
-                        help='File handle for the pipe')
-    parser.add_argument('--process-name', type=str, default=None,
-                        help='Identifier for debugging purpose')
+
+    parser = argparse.ArgumentParser("Command line parser")
+    parser.add_argument(
+        "--pipe", type=int, required=True, help="File handle for the pipe"
+    )
+    parser.add_argument(
+        "--process-name",
+        type=str,
+        default=None,
+        help="Identifier for debugging purpose",
+    )
 
     args = parser.parse_args()
 
     info = {}
     exitcode = 1
     try:
-        with os.fdopen(args.pipe, 'rb') as from_parent:
+        with os.fdopen(args.pipe, "rb") as from_parent:
             process.current_process()._inheriting = True
             try:
                 prep_data = pickle.load(from_parent)
@@ -169,12 +179,13 @@ def thread_is_spawning():
 
         exitcode = process_obj._bootstrap()
     except Exception:
-        print('\n\n' + '-' * 80)
-        print(f'{args.process_name} failed with traceback: ')
-        print('-' * 80)
+        print("\n\n" + "-" * 80)
+        print(f"{args.process_name} failed with traceback: ")
+        print("-" * 80)
         import traceback
+
         print(traceback.format_exc())
-        print('\n' + '-' * 80)
+        print("\n" + "-" * 80)
     finally:
         if from_parent is not None:
             from_parent.close()
diff --git a/loky/backend/popen_loky_win32.py b/loky/backend/popen_loky_win32.py
index c07fb46d..e72fea1b 100644
--- a/loky/backend/popen_loky_win32.py
+++ b/loky/backend/popen_loky_win32.py
@@ -11,7 +11,7 @@
 from . import reduction, spawn
 
 
-__all__ = ['Popen']
+__all__ = ["Popen"]
 
 #
 #
@@ -22,8 +22,9 @@ def _path_eq(p1, p2):
     return p1 == p2 or os.path.normcase(p1) == os.path.normcase(p2)
 
 
-WINENV = (hasattr(sys, "_base_executable")
-          and not _path_eq(sys.executable, sys._base_executable))
+WINENV = hasattr(sys, "_base_executable") and not _path_eq(
+    sys.executable, sys._base_executable
+)
 
 #
 # We define a Popen class similar to the one from subprocess, but
@@ -32,14 +33,16 @@ def _path_eq(p1, p2):
 
 
 class Popen(_Popen):
-    '''
+    """
     Start a subprocess to run the code of a process object
-    '''
-    method = 'loky'
+    """
+
+    method = "loky"
 
     def __init__(self, process_obj):
         prep_data = spawn.get_preparation_data(
-            process_obj._name, getattr(process_obj, "init_main_module", True))
+            process_obj._name, getattr(process_obj, "init_main_module", True)
+        )
 
         # read end of pipe will be "stolen" by the child process
         # -- see spawn_main() in spawn.py.
@@ -48,7 +51,7 @@ def __init__(self, process_obj):
         os.close(rfd)
 
         cmd = get_command_line(parent_pid=os.getpid(), pipe_handle=rhandle)
-        cmd = ' '.join(f'"{x}"' for x in cmd)
+        cmd = " ".join(f'"{x}"' for x in cmd)
 
         python_exe = spawn.get_executable()
 
@@ -62,7 +65,7 @@ def __init__(self, process_obj):
             child_env["__PYVENV_LAUNCHER__"] = sys.executable
 
         try:
-            with open(wfd, 'wb') as to_child:
+            with open(wfd, "wb") as to_child:
                 # start process
                 try:
                     # This flag allows to pass inheritable handles from the
@@ -74,9 +77,16 @@ def __init__(self, process_obj):
                     # be used instead.
                     inherit = True
                     hp, ht, pid, _ = _winapi.CreateProcess(
-                        python_exe, cmd,
-                        None, None, inherit, 0,
-                        child_env, None, None)
+                        python_exe,
+                        cmd,
+                        None,
+                        None,
+                        inherit,
+                        0,
+                        child_env,
+                        None,
+                        None,
+                    )
                     _winapi.CloseHandle(ht)
                 except BaseException:
                     _winapi.CloseHandle(rhandle)
@@ -111,23 +121,25 @@ def duplicate_for_child(self, handle):
 
 
 def get_command_line(pipe_handle, **kwds):
-    '''
-    Returns prefix of command line used for spawning a child process
-    '''
-    if getattr(sys, 'frozen', False):
-        return [sys.executable, '--multiprocessing-fork', pipe_handle]
+    """Returns prefix of command line used for spawning a child process."""
+    if getattr(sys, "frozen", False):
+        return [sys.executable, "--multiprocessing-fork", pipe_handle]
     else:
-        prog = 'from loky.backend.popen_loky_win32 import main; main()'
+        prog = "from loky.backend.popen_loky_win32 import main; main()"
         opts = util._args_from_interpreter_flags()
-        return [spawn.get_executable(), *opts,
-                '-c', prog, '--multiprocessing-fork', pipe_handle]
+        return [
+            spawn.get_executable(),
+            *opts,
+            "-c",
+            prog,
+            "--multiprocessing-fork",
+            pipe_handle,
+        ]
 
 
 def is_forking(argv):
-    '''
-    Return whether commandline indicates we are forking
-    '''
-    if len(argv) >= 2 and argv[1] == '--multiprocessing-fork':
+    """Return whether commandline indicates we are forking."""
+    if len(argv) >= 2 and argv[1] == "--multiprocessing-fork":
         assert len(argv) == 3
         return True
     else:
@@ -135,14 +147,12 @@ def is_forking(argv):
 
 
 def main():
-    '''
-    Run code specified by data received over pipe
-    '''
+    """Run code specified by data received over pipe."""
     assert is_forking(sys.argv)
 
     handle = int(sys.argv[-1])
     fd = msvcrt.open_osfhandle(handle, os.O_RDONLY)
-    from_parent = os.fdopen(fd, 'rb')
+    from_parent = os.fdopen(fd, "rb")
 
     process.current_process()._inheriting = True
     preparation_data = load(from_parent)
diff --git a/loky/backend/process.py b/loky/backend/process.py
index eafde66d..35625509 100644
--- a/loky/backend/process.py
+++ b/loky/backend/process.py
@@ -11,14 +11,27 @@
 
 
 class LokyProcess(BaseProcess):
-    _start_method = 'loky'
+    _start_method = "loky"
 
-    def __init__(self, group=None, target=None, name=None, args=(),
-                 kwargs={}, daemon=None, init_main_module=False,
-                 env=None):
+    def __init__(
+        self,
+        group=None,
+        target=None,
+        name=None,
+        args=(),
+        kwargs={},
+        daemon=None,
+        init_main_module=False,
+        env=None,
+    ):
         super().__init__(
-            group=group, target=target, name=name, args=args,
-            kwargs=kwargs, daemon=daemon)
+            group=group,
+            target=target,
+            name=name,
+            args=args,
+            kwargs=kwargs,
+            daemon=daemon,
+        )
         self.env = {} if env is None else env
         self.authkey = self.authkey
         self.init_main_module = init_main_module
@@ -33,26 +46,40 @@ def _Popen(process_obj):
 
 
 class LokyInitMainProcess(LokyProcess):
-    _start_method = 'loky_init_main'
+    _start_method = "loky_init_main"
 
-    def __init__(self, group=None, target=None, name=None, args=(),
-                 kwargs={}, daemon=None):
+    def __init__(
+        self,
+        group=None,
+        target=None,
+        name=None,
+        args=(),
+        kwargs={},
+        daemon=None,
+    ):
         super().__init__(
-            group=group, target=target, name=name, args=args, kwargs=kwargs,
-            daemon=daemon, init_main_module=True)
+            group=group,
+            target=target,
+            name=name,
+            args=args,
+            kwargs=kwargs,
+            daemon=daemon,
+            init_main_module=True,
+        )
 
 
 #
 # We subclass bytes to avoid accidental transmission of auth keys over network
 #
 
+
 class AuthenticationKey(bytes):
     def __reduce__(self):
         try:
             assert_spawning(self)
         except RuntimeError:
             raise TypeError(
-                'Pickling an AuthenticationKey object is '
-                'disallowed for security reasons'
+                "Pickling an AuthenticationKey object is "
+                "disallowed for security reasons"
             )
         return AuthenticationKey, (bytes(self),)
diff --git a/loky/backend/queues.py b/loky/backend/queues.py
index 4113b89f..5afd99b4 100644
--- a/loky/backend/queues.py
+++ b/loky/backend/queues.py
@@ -24,11 +24,10 @@
 from .reduction import dumps
 
 
-__all__ = ['Queue', 'SimpleQueue', 'Full']
+__all__ = ["Queue", "SimpleQueue", "Full"]
 
 
 class Queue(mp_Queue):
-
     def __init__(self, maxsize=0, reducers=None, ctx=None):
         super().__init__(maxsize=maxsize, ctx=ctx)
         self._reducers = reducers
@@ -36,14 +35,30 @@ def __init__(self, maxsize=0, reducers=None, ctx=None):
     # Use custom queue set/get state to be able to reduce the custom reducers
     def __getstate__(self):
         assert_spawning(self)
-        return (self._ignore_epipe, self._maxsize, self._reader, self._writer,
-                self._reducers, self._rlock, self._wlock, self._sem,
-                self._opid)
+        return (
+            self._ignore_epipe,
+            self._maxsize,
+            self._reader,
+            self._writer,
+            self._reducers,
+            self._rlock,
+            self._wlock,
+            self._sem,
+            self._opid,
+        )
 
     def __setstate__(self, state):
-        (self._ignore_epipe, self._maxsize, self._reader, self._writer,
-         self._reducers, self._rlock, self._wlock, self._sem,
-         self._opid) = state
+        (
+            self._ignore_epipe,
+            self._maxsize,
+            self._reader,
+            self._writer,
+            self._reducers,
+            self._rlock,
+            self._wlock,
+            self._sem,
+            self._opid,
+        ) = state
         if sys.version_info >= (3, 9):
             self._reset()
         else:
@@ -51,22 +66,30 @@ def __setstate__(self, state):
 
     # Overload _start_thread to correctly call our custom _feed
     def _start_thread(self):
-        util.debug('Queue._start_thread()')
+        util.debug("Queue._start_thread()")
 
         # Start thread which transfers data from buffer to pipe
         self._buffer.clear()
         self._thread = threading.Thread(
             target=Queue._feed,
-            args=(self._buffer, self._notempty, self._send_bytes,
-                  self._wlock, self._writer.close, self._reducers,
-                  self._ignore_epipe, self._on_queue_feeder_error, self._sem),
-            name='QueueFeederThread'
+            args=(
+                self._buffer,
+                self._notempty,
+                self._send_bytes,
+                self._wlock,
+                self._writer.close,
+                self._reducers,
+                self._ignore_epipe,
+                self._on_queue_feeder_error,
+                self._sem,
+            ),
+            name="QueueFeederThread",
         )
         self._thread.daemon = True
 
-        util.debug('doing self._thread.start()')
+        util.debug("doing self._thread.start()")
         self._thread.start()
-        util.debug('... done self._thread.start()')
+        util.debug("... done self._thread.start()")
 
         # On process exit we will wait for data to be flushed to pipe.
         #
@@ -74,32 +97,43 @@ def _start_thread(self):
         # processes which use the queue will be descendants of this
         # process.  Therefore waiting for the queue to be flushed
         # is pointless once all the child processes have been joined.
-        created_by_this_process = (self._opid == os.getpid())
+        created_by_this_process = self._opid == os.getpid()
         if not self._joincancelled and not created_by_this_process:
             self._jointhread = util.Finalize(
-                self._thread, Queue._finalize_join,
+                self._thread,
+                Queue._finalize_join,
                 [weakref.ref(self._thread)],
-                exitpriority=-5
+                exitpriority=-5,
             )
 
         # Send sentinel to the thread queue object when garbage collected
         self._close = util.Finalize(
-            self, Queue._finalize_close,
+            self,
+            Queue._finalize_close,
             [self._buffer, self._notempty],
-            exitpriority=10
+            exitpriority=10,
         )
 
     # Overload the _feed methods to use our custom pickling strategy.
     @staticmethod
-    def _feed(buffer, notempty, send_bytes, writelock, close, reducers,
-              ignore_epipe, onerror, queue_sem):
-        util.debug('starting thread to feed data to pipe')
+    def _feed(
+        buffer,
+        notempty,
+        send_bytes,
+        writelock,
+        close,
+        reducers,
+        ignore_epipe,
+        onerror,
+        queue_sem,
+    ):
+        util.debug("starting thread to feed data to pipe")
         nacquire = notempty.acquire
         nrelease = notempty.release
         nwait = notempty.wait
         bpopleft = buffer.popleft
         sentinel = _sentinel
-        if sys.platform != 'win32':
+        if sys.platform != "win32":
             wacquire = writelock.acquire
             wrelease = writelock.release
         else:
@@ -117,7 +151,7 @@ def _feed(buffer, notempty, send_bytes, writelock, close, reducers,
                     while True:
                         obj = bpopleft()
                         if obj is sentinel:
-                            util.debug('feeder thread got sentinel -- exiting')
+                            util.debug("feeder thread got sentinel -- exiting")
                             close()
                             return
 
@@ -136,14 +170,14 @@ def _feed(buffer, notempty, send_bytes, writelock, close, reducers,
                 except IndexError:
                     pass
             except BaseException as e:
-                if ignore_epipe and getattr(e, 'errno', 0) == errno.EPIPE:
+                if ignore_epipe and getattr(e, "errno", 0) == errno.EPIPE:
                     return
                 # Since this runs in a daemon thread the resources it uses
                 # may be become unusable while the process is cleaning up.
                 # We ignore errors which happen after the process has
                 # started to cleanup.
                 if util.is_exiting():
-                    util.info(f'error in queue thread: {e}')
+                    util.info(f"error in queue thread: {e}")
                     return
                 else:
                     queue_sem.release()
@@ -155,11 +189,11 @@ def _on_queue_feeder_error(self, e, obj):
         raises an exception.  For overriding by concurrent.futures.
         """
         import traceback
+
         traceback.print_exc()
 
 
 class SimpleQueue(mp_SimpleQueue):
-
     def __init__(self, reducers=None, ctx=None):
         super().__init__(ctx=ctx)
 
@@ -173,12 +207,22 @@ def close(self):
     # Use custom queue set/get state to be able to reduce the custom reducers
     def __getstate__(self):
         assert_spawning(self)
-        return (self._reader, self._writer, self._reducers, self._rlock,
-                self._wlock)
+        return (
+            self._reader,
+            self._writer,
+            self._reducers,
+            self._rlock,
+            self._wlock,
+        )
 
     def __setstate__(self, state):
-        (self._reader, self._writer, self._reducers, self._rlock,
-         self._wlock) = state
+        (
+            self._reader,
+            self._writer,
+            self._reducers,
+            self._rlock,
+            self._wlock,
+        ) = state
 
     # Overload put to use our customizable reducer
     def put(self, obj):
diff --git a/loky/backend/reduction.py b/loky/backend/reduction.py
index c3de02ec..69e64855 100644
--- a/loky/backend/reduction.py
+++ b/loky/backend/reduction.py
@@ -27,6 +27,7 @@
 def register(type_, reduce_function):
     _dispatch_table[type_] = reduce_function
 
+
 ###############################################################################
 # Registers extra pickling routines to improve picklization  for loky
 
@@ -80,6 +81,7 @@ def _rebuild_partial(func, args, keywords):
 # global variable to change the pickler behavior
 try:
     import cloudpickle  # noqa: F401
+
     DEFAULT_ENV = "cloudpickle"
 except ImportError:
     # If cloudpickle is not present, fallback to pickle
@@ -110,12 +112,15 @@ def set_loky_pickler(loky_pickler=None):
     else:
         try:
             from importlib import import_module
+
             module_pickle = import_module(loky_pickler)
             loky_pickler_cls = module_pickle.Pickler
         except (ImportError, AttributeError) as e:
-            extra_info = ("\nThis error occurred while setting loky_pickler to"
-                          f" '{loky_pickler}', as required by the env variable "
-                          "LOKY_PICKLER or the function set_loky_pickler.")
+            extra_info = (
+                "\nThis error occurred while setting loky_pickler to"
+                f" '{loky_pickler}', as required by the env variable "
+                "LOKY_PICKLER or the function set_loky_pickler."
+            )
             e.args = (e.args[0] + extra_info,) + e.args[1:]
             e.msg = e.args[0]
             raise e
@@ -176,8 +181,7 @@ def __init__(self, writer, reducers=None, protocol=HIGHEST_PROTOCOL):
                 self.register(type, reduce_func)
 
         def register(self, type, reduce_func):
-            """Attach a reducer function to a given type in the dispatch table.
-            """
+            """Attach a reducer function to a given type in the dispatch table."""
             self.dispatch_table[type] = reduce_func
 
     _LokyPickler = CustomizablePickler
@@ -199,7 +203,7 @@ def get_loky_pickler():
 
 
 def dump(obj, file, reducers=None, protocol=None):
-    '''Replacement for pickle.dump() using _LokyPickler.'''
+    """Replacement for pickle.dump() using _LokyPickler."""
     global _LokyPickler
     _LokyPickler(file, reducers=reducers, protocol=protocol).dump(obj)
 
@@ -216,4 +220,5 @@ def dumps(obj, reducers=None, protocol=None):
 
 if sys.platform == "win32":
     from multiprocessing.reduction import duplicate
+
     __all__ += ["duplicate"]
diff --git a/loky/backend/resource_tracker.py b/loky/backend/resource_tracker.py
index d84504e1..25204a7a 100644
--- a/loky/backend/resource_tracker.py
+++ b/loky/backend/resource_tracker.py
@@ -60,25 +60,21 @@
     from multiprocessing.reduction import duplicate
 
 
-__all__ = ['ensure_running', 'register', 'unregister']
+__all__ = ["ensure_running", "register", "unregister"]
 
-_HAVE_SIGMASK = hasattr(signal, 'pthread_sigmask')
+_HAVE_SIGMASK = hasattr(signal, "pthread_sigmask")
 _IGNORED_SIGNALS = (signal.SIGINT, signal.SIGTERM)
 
-_CLEANUP_FUNCS = {
-    'folder': shutil.rmtree,
-    'file': os.unlink
-}
+_CLEANUP_FUNCS = {"folder": shutil.rmtree, "file": os.unlink}
 
 if os.name == "posix":
-    _CLEANUP_FUNCS['semlock'] = sem_unlink
+    _CLEANUP_FUNCS["semlock"] = sem_unlink
 
 
 VERBOSE = False
 
 
 class ResourceTracker:
-
     def __init__(self):
         self._lock = threading.Lock()
         self._fd = None
@@ -89,10 +85,10 @@ def getfd(self):
         return self._fd
 
     def ensure_running(self):
-        '''Make sure that resource tracker process is running.
+        """Make sure that resource tracker process is running.
 
         This can be run from any process.  Usually a child process will use
-        the resource created by its parent.'''
+        the resource created by its parent."""
         with self._lock:
             if self._fd is not None:
                 # resource tracker was launched before, is it still running?
@@ -114,9 +110,11 @@ def ensure_running(self):
                 self._fd = None
                 self._pid = None
 
-                warnings.warn('resource_tracker: process died unexpectedly, '
-                              'relaunching.  Some folders/sempahores might '
-                              'leak.')
+                warnings.warn(
+                    "resource_tracker: process died unexpectedly, "
+                    "relaunching.  Some folders/sempahores might "
+                    "leak."
+                )
 
             fds_to_pass = []
             try:
@@ -130,12 +128,12 @@ def ensure_running(self):
                 os.close(r)
                 r = _r
 
-            cmd = f'from {main.__module__} import main; main({r}, {VERBOSE})'
+            cmd = f"from {main.__module__} import main; main({r}, {VERBOSE})"
             try:
                 fds_to_pass.append(r)
                 # process will out live us, so no need to wait on pid
                 exe = spawn.get_executable()
-                args = [exe, *util._args_from_interpreter_flags(), '-c', cmd]
+                args = [exe, *util._args_from_interpreter_flags(), "-c", cmd]
                 util.debug(f"launching resource tracker: {args}")
                 # bpo-33613: Register a signal mask that will block the
                 # signals.  This signal mask will be inherited by the child
@@ -145,13 +143,15 @@ def ensure_running(self):
                 # unregistered after spawning the child.
                 try:
                     if _HAVE_SIGMASK:
-                        signal.pthread_sigmask(signal.SIG_BLOCK,
-                                               _IGNORED_SIGNALS)
+                        signal.pthread_sigmask(
+                            signal.SIG_BLOCK, _IGNORED_SIGNALS
+                        )
                     pid = spawnv_passfds(exe, args, fds_to_pass)
                 finally:
                     if _HAVE_SIGMASK:
-                        signal.pthread_sigmask(signal.SIG_UNBLOCK,
-                                               _IGNORED_SIGNALS)
+                        signal.pthread_sigmask(
+                            signal.SIG_UNBLOCK, _IGNORED_SIGNALS
+                        )
             except BaseException:
                 os.close(w)
                 raise
@@ -165,26 +165,26 @@ def ensure_running(self):
                     os.close(r)
 
     def _check_alive(self):
-        '''Check for the existence of the resource tracker process.'''
+        """Check for the existence of the resource tracker process."""
         try:
-            self._send('PROBE', '', '')
+            self._send("PROBE", "", "")
         except BrokenPipeError:
             return False
         else:
             return True
 
     def register(self, name, rtype):
-        '''Register a named resource, and increment its refcount.'''
+        """Register a named resource, and increment its refcount."""
         self.ensure_running()
-        self._send('REGISTER', name, rtype)
+        self._send("REGISTER", name, rtype)
 
     def unregister(self, name, rtype):
-        '''Unregister a named resource with resource tracker.'''
+        """Unregister a named resource with resource tracker."""
         self.ensure_running()
-        self._send('UNREGISTER', name, rtype)
+        self._send("UNREGISTER", name, rtype)
 
     def maybe_unlink(self, name, rtype):
-        '''Decrement the refcount of a resource, and delete it if it hits 0'''
+        """Decrement the refcount of a resource, and delete it if it hits 0"""
         self.ensure_running()
         self._send("MAYBE_UNLINK", name, rtype)
 
@@ -192,8 +192,8 @@ def _send(self, cmd, name, rtype):
         if len(name) > 512:
             # posix guarantees that writes to a pipe of less than PIPE_BUF
             # bytes are atomic, and that PIPE_BUF >= 512
-            raise ValueError('name too long')
-        msg = f'{cmd}:{name}:{rtype}\n'.encode('ascii')
+            raise ValueError("name too long")
+        msg = f"{cmd}:{name}:{rtype}\n".encode("ascii")
         nbytes = os.write(self._fd, msg)
         assert nbytes == len(msg)
 
@@ -207,7 +207,7 @@ def _send(self, cmd, name, rtype):
 
 
 def main(fd, verbose=0):
-    '''Run resource tracker.'''
+    """Run resource tracker."""
     # protect the process from ^C and "killall python" etc
     if verbose:
         util.log_to_stderr(level=util.DEBUG)
@@ -232,30 +232,33 @@ def main(fd, verbose=0):
         # keep track of registered/unregistered resources
         if sys.platform == "win32":
             fd = msvcrt.open_osfhandle(fd, os.O_RDONLY)
-        with open(fd, 'rb') as f:
+        with open(fd, "rb") as f:
             while True:
                 line = f.readline()
-                if line == b'':  # EOF
+                if line == b"":  # EOF
                     break
                 try:
-                    splitted = line.strip().decode('ascii').split(':')
+                    splitted = line.strip().decode("ascii").split(":")
                     # name can potentially contain separator symbols (for
                     # instance folders on Windows)
                     cmd, name, rtype = (
-                        splitted[0], ':'.join(splitted[1:-1]), splitted[-1])
+                        splitted[0],
+                        ":".join(splitted[1:-1]),
+                        splitted[-1],
+                    )
 
-                    if cmd == 'PROBE':
+                    if cmd == "PROBE":
                         continue
 
                     if rtype not in _CLEANUP_FUNCS:
                         raise ValueError(
-                            f'Cannot register {name} for automatic cleanup: '
-                            f'unknown resource type ({rtype}). Resource type '
-                            'should be one of the following: '
-                            f'{list(_CLEANUP_FUNCS.keys())}'
+                            f"Cannot register {name} for automatic cleanup: "
+                            f"unknown resource type ({rtype}). Resource type "
+                            "should be one of the following: "
+                            f"{list(_CLEANUP_FUNCS.keys())}"
                         )
 
-                    if cmd == 'REGISTER':
+                    if cmd == "REGISTER":
                         if name not in registry[rtype]:
                             registry[rtype][name] = 1
                         else:
@@ -267,14 +270,14 @@ def main(fd, verbose=0):
                                 f"{rtype} {name} "
                                 f"(current {registry[rtype][name]})"
                             )
-                    elif cmd == 'UNREGISTER':
+                    elif cmd == "UNREGISTER":
                         del registry[rtype][name]
                         if verbose:
                             util.debug(
                                 f"[ResourceTracker] unregister {name} {rtype}: "
                                 f"registry({len(registry)})"
                             )
-                    elif cmd == 'MAYBE_UNLINK':
+                    elif cmd == "MAYBE_UNLINK":
                         registry[rtype][name] -= 1
                         if verbose:
                             util.debug(
@@ -293,10 +296,11 @@ def main(fd, verbose=0):
                                 _CLEANUP_FUNCS[rtype](name)
                             except Exception as e:
                                 warnings.warn(
-                                    f'resource_tracker: {name}: {e!r}')
+                                    f"resource_tracker: {name}: {e!r}"
+                                )
 
                     else:
-                        raise RuntimeError(f'unrecognized command {cmd!r}')
+                        raise RuntimeError(f"unrecognized command {cmd!r}")
                 except BaseException:
                     try:
                         sys.excepthook(*sys.exc_info())
@@ -308,9 +312,9 @@ def _unlink_resources(rtype_registry, rtype):
             if rtype_registry:
                 try:
                     warnings.warn(
-                        'resource_tracker: There appear to be '
-                        f'{len(rtype_registry)} leaked {rtype} objects to '
-                        'clean up at shutdown'
+                        "resource_tracker: There appear to be "
+                        f"{len(rtype_registry)} leaked {rtype} objects to "
+                        "clean up at shutdown"
                     )
                 except Exception:
                     pass
@@ -323,7 +327,7 @@ def _unlink_resources(rtype_registry, rtype):
                     if verbose:
                         util.debug(f"[ResourceTracker] unlink {name}")
                 except Exception as e:
-                    warnings.warn(f'resource_tracker: {name}: {e!r}')
+                    warnings.warn(f"resource_tracker: {name}: {e!r}")
 
         for rtype, rtype_registry in registry.items():
             if rtype == "folder":
@@ -348,6 +352,7 @@ def _unlink_resources(rtype_registry, rtype):
 # Start a program with only specified fds kept open
 #
 
+
 def spawnv_passfds(path, args, passfds):
     passfds = sorted(passfds)
     if sys.platform != "win32":
@@ -355,16 +360,18 @@ def spawnv_passfds(path, args, passfds):
         try:
             from .reduction import _mk_inheritable
             from .fork_exec import fork_exec
+
             _pass = [_mk_inheritable(fd) for fd in passfds]
             return fork_exec(args, _pass)
         finally:
             os.close(errpipe_read)
             os.close(errpipe_write)
     else:
-        cmd = ' '.join(f'"{x}"' for x in args)
+        cmd = " ".join(f'"{x}"' for x in args)
         try:
             _, ht, pid, _ = _winapi.CreateProcess(
-                path, cmd, None, None, True, 0, None, None, None)
+                path, cmd, None, None, True, 0, None, None, None
+            )
             _winapi.CloseHandle(ht)
         except BaseException:
             pass
diff --git a/loky/backend/spawn.py b/loky/backend/spawn.py
index 3a9cc2dd..589c51e3 100644
--- a/loky/backend/spawn.py
+++ b/loky/backend/spawn.py
@@ -9,21 +9,23 @@
 import os
 import sys
 import runpy
+import textwrap
 import types
 from multiprocessing import process, util
 
 
-if sys.platform != 'win32':
+if sys.platform != "win32":
     WINEXE = False
     WINSERVICE = False
 else:
     import msvcrt
     from multiprocessing.reduction import duplicate
-    WINEXE = (sys.platform == 'win32' and getattr(sys, 'frozen', False))
+
+    WINEXE = sys.platform == "win32" and getattr(sys, "frozen", False)
     WINSERVICE = sys.executable.lower().endswith("pythonservice.exe")
 
 if WINSERVICE:
-    _python_exe = os.path.join(sys.exec_prefix, 'python.exe')
+    _python_exe = os.path.join(sys.exec_prefix, "python.exe")
 else:
     _python_exe = sys.executable
 
@@ -33,27 +35,29 @@ def get_executable():
 
 
 def _check_not_importing_main():
-    if getattr(process.current_process(), '_inheriting', False):
-        raise RuntimeError('''
-        An attempt has been made to start a new process before the
-        current process has finished its bootstrapping phase.
-
-        This probably means that you are not using fork to start your
-        child processes and you have forgotten to use the proper idiom
-        in the main module:
-
-            if __name__ == '__main__':
-                freeze_support()
-                ...
-
-        The "freeze_support()" line can be omitted if the program
-        is not going to be frozen to produce an executable.''')
+    if getattr(process.current_process(), "_inheriting", False):
+        raise RuntimeError(
+            textwrap.dedent(
+                """\
+            An attempt has been made to start a new process before the
+            current process has finished its bootstrapping phase.
+
+            This probably means that you are not using fork to start your
+            child processes and you have forgotten to use the proper idiom
+            in the main module:
+
+                if __name__ == '__main__':
+                    freeze_support()
+                    ...
+
+            The "freeze_support()" line can be omitted if the program
+            is not going to be frozen to produce an executable."""
+            )
+        )
 
 
 def get_preparation_data(name, init_main_module=True):
-    '''
-    Return info about parent needed by child to unpickle process object
-    '''
+    """Return info about parent needed by child to unpickle process object."""
     _check_not_importing_main()
     d = dict(
         log_to_stderr=util._log_to_stderr,
@@ -61,31 +65,33 @@ def get_preparation_data(name, init_main_module=True):
         name=name,
         sys_argv=sys.argv,
         orig_dir=process.ORIGINAL_DIR,
-        dir=os.getcwd()
+        dir=os.getcwd(),
     )
 
     # Send sys_path and make sure the current directory will not be changed
-    d['sys_path'] = [p if p != '' else process.ORIGINAL_DIR for p in sys.path]
+    d["sys_path"] = [p if p != "" else process.ORIGINAL_DIR for p in sys.path]
 
     # Make sure to pass the information if the multiprocessing logger is active
     if util._logger is not None:
-        d['log_level'] = util._logger.getEffectiveLevel()
+        d["log_level"] = util._logger.getEffectiveLevel()
         if util._logger.handlers:
             h = util._logger.handlers[0]
-            d['log_fmt'] = h.formatter._fmt
+            d["log_fmt"] = h.formatter._fmt
 
     # Tell the child how to communicate with the resource_tracker
     from .resource_tracker import _resource_tracker
+
     _resource_tracker.ensure_running()
     d["tracker_args"] = {"pid": _resource_tracker._pid}
     if sys.platform == "win32":
         child_w = duplicate(
-            msvcrt.get_osfhandle(_resource_tracker._fd), inheritable=True)
+            msvcrt.get_osfhandle(_resource_tracker._fd), inheritable=True
+        )
         d["tracker_args"]["fh"] = child_w
     else:
         d["tracker_args"]["fd"] = _resource_tracker._fd
 
-    if sys.version_info >= (3, 8) and os.name == 'posix':
+    if sys.version_info >= (3, 8) and os.name == "posix":
         # joblib/loky#242: allow loky processes to retrieve the resource
         # tracker of their parent in case the child processes depickles
         # shared_memory objects, that are still tracked by multiprocessing's
@@ -95,33 +101,37 @@ def get_preparation_data(name, init_main_module=True):
         # to force registration of shared_memory segments via loky's
         # resource_tracker.
         from multiprocessing.resource_tracker import (
-            _resource_tracker as mp_resource_tracker
+            _resource_tracker as mp_resource_tracker,
         )
+
         # multiprocessing's resource_tracker must be running before loky
         # process is created (othewise the child won't be able to use it if it
         # is created later on)
         mp_resource_tracker.ensure_running()
         d["mp_tracker_args"] = {
-            'fd': mp_resource_tracker._fd, 'pid': mp_resource_tracker._pid
+            "fd": mp_resource_tracker._fd,
+            "pid": mp_resource_tracker._pid,
         }
 
     # Figure out whether to initialise main in the subprocess as a module
     # or through direct execution (or to leave it alone entirely)
     if init_main_module:
-        main_module = sys.modules['__main__']
+        main_module = sys.modules["__main__"]
         try:
             main_mod_name = getattr(main_module.__spec__, "name", None)
         except BaseException:
             main_mod_name = None
         if main_mod_name is not None:
-            d['init_main_from_name'] = main_mod_name
-        elif sys.platform != 'win32' or (not WINEXE and not WINSERVICE):
-            main_path = getattr(main_module, '__file__', None)
+            d["init_main_from_name"] = main_mod_name
+        elif sys.platform != "win32" or (not WINEXE and not WINSERVICE):
+            main_path = getattr(main_module, "__file__", None)
             if main_path is not None:
-                if (not os.path.isabs(main_path) and
-                        process.ORIGINAL_DIR is not None):
+                if (
+                    not os.path.isabs(main_path)
+                    and process.ORIGINAL_DIR is not None
+                ):
                     main_path = os.path.join(process.ORIGINAL_DIR, main_path)
-                d['init_main_from_path'] = os.path.normpath(main_path)
+                d["init_main_from_path"] = os.path.normpath(main_path)
 
     return d
 
@@ -133,58 +143,59 @@ def get_preparation_data(name, init_main_module=True):
 
 
 def prepare(data):
-    '''
-    Try to get current process ready to unpickle process object
-    '''
-    if 'name' in data:
-        process.current_process().name = data['name']
+    """Try to get current process ready to unpickle process object."""
+    if "name" in data:
+        process.current_process().name = data["name"]
 
-    if 'authkey' in data:
-        process.current_process().authkey = data['authkey']
+    if "authkey" in data:
+        process.current_process().authkey = data["authkey"]
 
-    if 'log_to_stderr' in data and data['log_to_stderr']:
+    if "log_to_stderr" in data and data["log_to_stderr"]:
         util.log_to_stderr()
 
-    if 'log_level' in data:
-        util.get_logger().setLevel(data['log_level'])
+    if "log_level" in data:
+        util.get_logger().setLevel(data["log_level"])
 
-    if 'log_fmt' in data:
+    if "log_fmt" in data:
         import logging
+
         util.get_logger().handlers[0].setFormatter(
-            logging.Formatter(data['log_fmt'])
+            logging.Formatter(data["log_fmt"])
         )
 
-    if 'sys_path' in data:
-        sys.path = data['sys_path']
+    if "sys_path" in data:
+        sys.path = data["sys_path"]
 
-    if 'sys_argv' in data:
-        sys.argv = data['sys_argv']
+    if "sys_argv" in data:
+        sys.argv = data["sys_argv"]
 
-    if 'dir' in data:
-        os.chdir(data['dir'])
+    if "dir" in data:
+        os.chdir(data["dir"])
 
-    if 'orig_dir' in data:
-        process.ORIGINAL_DIR = data['orig_dir']
+    if "orig_dir" in data:
+        process.ORIGINAL_DIR = data["orig_dir"]
 
-    if 'mp_tracker_args' in data:
+    if "mp_tracker_args" in data:
         from multiprocessing.resource_tracker import (
-            _resource_tracker as mp_resource_tracker
+            _resource_tracker as mp_resource_tracker,
         )
-        mp_resource_tracker._fd = data['mp_tracker_args']['fd']
-        mp_resource_tracker._pid = data['mp_tracker_args']['pid']
-    if 'tracker_args' in data:
+
+        mp_resource_tracker._fd = data["mp_tracker_args"]["fd"]
+        mp_resource_tracker._pid = data["mp_tracker_args"]["pid"]
+    if "tracker_args" in data:
         from .resource_tracker import _resource_tracker
-        _resource_tracker._pid = data["tracker_args"]['pid']
-        if sys.platform == 'win32':
+
+        _resource_tracker._pid = data["tracker_args"]["pid"]
+        if sys.platform == "win32":
             handle = data["tracker_args"]["fh"]
             _resource_tracker._fd = msvcrt.open_osfhandle(handle, 0)
         else:
             _resource_tracker._fd = data["tracker_args"]["fd"]
 
-    if 'init_main_from_name' in data:
-        _fixup_main_from_name(data['init_main_from_name'])
-    elif 'init_main_from_path' in data:
-        _fixup_main_from_path(data['init_main_from_path'])
+    if "init_main_from_name" in data:
+        _fixup_main_from_name(data["init_main_from_name"])
+    elif "init_main_from_path" in data:
+        _fixup_main_from_path(data["init_main_from_path"])
 
 
 # Multiprocessing module helpers to fix up the main module in
@@ -194,7 +205,7 @@ def _fixup_main_from_name(mod_name):
     # their "main only" code unconditionally, so we don't even try to
     # populate anything in __main__, nor do we make any changes to
     # __main__ attributes
-    current_main = sys.modules['__main__']
+    current_main = sys.modules["__main__"]
     if mod_name == "__main__" or mod_name.endswith(".__main__"):
         return
 
@@ -207,28 +218,28 @@ def _fixup_main_from_name(mod_name):
     # the normal __main__ an alias to that
     old_main_modules.append(current_main)
     main_module = types.ModuleType("__mp_main__")
-    main_content = runpy.run_module(mod_name,
-                                    run_name="__mp_main__",
-                                    alter_sys=True)
+    main_content = runpy.run_module(
+        mod_name, run_name="__mp_main__", alter_sys=True
+    )
     main_module.__dict__.update(main_content)
-    sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
+    sys.modules["__main__"] = sys.modules["__mp_main__"] = main_module
 
 
 def _fixup_main_from_path(main_path):
     # If this process was forked, __main__ may already be populated
-    current_main = sys.modules['__main__']
+    current_main = sys.modules["__main__"]
 
     # Unfortunately, the main ipython launch script historically had no
     # "if __name__ == '__main__'" guard, so we work around that
     # by treating it like a __main__.py file
     # See https://github.com/ipython/ipython/issues/4698
     main_name = os.path.splitext(os.path.basename(main_path))[0]
-    if main_name == 'ipython':
+    if main_name == "ipython":
         return
 
     # Otherwise, if __file__ already has the setting we expect,
     # there's nothing more to do
-    if getattr(current_main, '__file__', None) == main_path:
+    if getattr(current_main, "__file__", None) == main_path:
         return
 
     # If the parent process has sent a path through rather than a module
@@ -236,7 +247,6 @@ def _fixup_main_from_path(main_path):
     # non-main code that needs to be executed
     old_main_modules.append(current_main)
     main_module = types.ModuleType("__mp_main__")
-    main_content = runpy.run_path(main_path,
-                                  run_name="__mp_main__")
+    main_content = runpy.run_path(main_path, run_name="__mp_main__")
     main_module.__dict__.update(main_content)
-    sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
+    sys.modules["__main__"] = sys.modules["__mp_main__"] = main_module
diff --git a/loky/backend/synchronize.py b/loky/backend/synchronize.py
index a9518a88..18db3e34 100644
--- a/loky/backend/synchronize.py
+++ b/loky/backend/synchronize.py
@@ -24,8 +24,13 @@
 from . import resource_tracker
 
 __all__ = [
-    'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', 'Event'
-    ]
+    "Lock",
+    "RLock",
+    "Semaphore",
+    "BoundedSemaphore",
+    "Condition",
+    "Event",
+]
 # Try to import the mp.synchronize module cleanly, if it fails
 # raise ImportError for platforms lacking a working sem_open implementation.
 # See issue 3770
@@ -33,10 +38,12 @@
     from _multiprocessing import SemLock as _SemLock
     from _multiprocessing import sem_unlink
 except ImportError:
-    raise ImportError("This platform lacks a functioning sem_open" +
-                      " implementation, therefore, the required" +
-                      " synchronization primitives needed will not" +
-                      " function, see issue 3770.")
+    raise ImportError(
+        "This platform lacks a functioning sem_open"
+        " implementation, therefore, the required"
+        " synchronization primitives needed will not"
+        " function, see issue 3770."
+    )
 
 #
 # Constants
@@ -50,6 +57,7 @@
 # Base class for semaphores and mutexes; wraps `_multiprocessing.SemLock`
 #
 
+
 class SemLock:
 
     _rand = tempfile._RandomNameSequence()
@@ -69,14 +77,12 @@ def __init__(self, kind, value, maxvalue, name=None):
                 else:
                     break
             else:  # pragma: no cover
-                raise FileExistsError('cannot find name for semaphore')
+                raise FileExistsError("cannot find name for semaphore")
         else:
-            self._semlock = _SemLock(
-                kind, value, maxvalue, name, unlink_now
-            )
+            self._semlock = _SemLock(kind, value, maxvalue, name, unlink_now)
         self.name = name
         util.debug(
-            f'created semlock with handle {self._semlock.handle} and name '
+            f"created semlock with handle {self._semlock.handle} and name "
             f'"{self.name}"'
         )
 
@@ -90,8 +96,9 @@ def _after_fork(obj):
         # When the object is garbage collected or the
         # process shuts down we unlink the semaphore name
         resource_tracker.register(self._semlock.name, "semlock")
-        util.Finalize(self, SemLock._cleanup, (self._semlock.name,),
-                      exitpriority=0)
+        util.Finalize(
+            self, SemLock._cleanup, (self._semlock.name,), exitpriority=0
+        )
 
     @staticmethod
     def _cleanup(name):
@@ -130,20 +137,20 @@ def __setstate__(self, state):
     @staticmethod
     def _make_name():
         # OSX does not support long names for semaphores
-        return f'/loky-{os.getpid()}-{next(SemLock._rand)}'
+        return f"/loky-{os.getpid()}-{next(SemLock._rand)}"
 
 
 #
 # Semaphore
 #
 
-class Semaphore(SemLock):
 
+class Semaphore(SemLock):
     def __init__(self, value=1):
         SemLock.__init__(self, SEMAPHORE, value, SEM_VALUE_MAX)
 
     def get_value(self):
-        if sys.platform == 'darwin':
+        if sys.platform == "darwin":
             raise NotImplementedError("OSX does not implement sem_getvalue")
         return self._semlock._get_value()
 
@@ -151,16 +158,16 @@ def __repr__(self):
         try:
             value = self._semlock._get_value()
         except Exception:
-            value = 'unknown'
-        return f'<{self.__class__.__name__}(value={value})>'
+            value = "unknown"
+        return f"<{self.__class__.__name__}(value={value})>"
 
 
 #
 # Bounded semaphore
 #
 
-class BoundedSemaphore(Semaphore):
 
+class BoundedSemaphore(Semaphore):
     def __init__(self, value=1):
         SemLock.__init__(self, SEMAPHORE, value, value)
 
@@ -168,10 +175,10 @@ def __repr__(self):
         try:
             value = self._semlock._get_value()
         except Exception:
-            value = 'unknown'
+            value = "unknown"
         return (
-            f'<{self.__class__.__name__}(value={value}, '
-            f'maxvalue={self._semlock.maxvalue})>'
+            f"<{self.__class__.__name__}(value={value}, "
+            f"maxvalue={self._semlock.maxvalue})>"
         )
 
 
@@ -179,8 +186,8 @@ def __repr__(self):
 # Non-recursive lock
 #
 
-class Lock(SemLock):
 
+class Lock(SemLock):
     def __init__(self):
         super().__init__(SEMAPHORE, 1, 1)
 
@@ -188,25 +195,25 @@ def __repr__(self):
         try:
             if self._semlock._is_mine():
                 name = process.current_process().name
-                if threading.current_thread().name != 'MainThread':
-                    name = f'{name}|{threading.current_thread().name}'
+                if threading.current_thread().name != "MainThread":
+                    name = f"{name}|{threading.current_thread().name}"
             elif self._semlock._get_value() == 1:
-                name = 'None'
+                name = "None"
             elif self._semlock._count() > 0:
-                name = 'SomeOtherThread'
+                name = "SomeOtherThread"
             else:
-                name = 'SomeOtherProcess'
+                name = "SomeOtherProcess"
         except Exception:
-            name = 'unknown'
-        return f'<{self.__class__.__name__}(owner={name})>'
+            name = "unknown"
+        return f"<{self.__class__.__name__}(owner={name})>"
 
 
 #
 # Recursive lock
 #
 
-class RLock(SemLock):
 
+class RLock(SemLock):
     def __init__(self):
         super().__init__(RECURSIVE_MUTEX, 1, 1)
 
@@ -214,26 +221,26 @@ def __repr__(self):
         try:
             if self._semlock._is_mine():
                 name = process.current_process().name
-                if threading.current_thread().name != 'MainThread':
-                    name = f'{name}|{threading.current_thread().name}'
+                if threading.current_thread().name != "MainThread":
+                    name = f"{name}|{threading.current_thread().name}"
                 count = self._semlock._count()
             elif self._semlock._get_value() == 1:
-                name, count = 'None', 0
+                name, count = "None", 0
             elif self._semlock._count() > 0:
-                name, count = 'SomeOtherThread', 'nonzero'
+                name, count = "SomeOtherThread", "nonzero"
             else:
-                name, count = 'SomeOtherProcess', 'nonzero'
+                name, count = "SomeOtherProcess", "nonzero"
         except Exception:
-            name, count = 'unknown', 'unknown'
-        return f'<{self.__class__.__name__}({name}, {count})>'
+            name, count = "unknown", "unknown"
+        return f"<{self.__class__.__name__}({name}, {count})>"
 
 
 #
 # Condition variable
 #
 
-class Condition:
 
+class Condition:
     def __init__(self, lock=None):
         self._lock = lock or RLock()
         self._sleeping_count = Semaphore(0)
@@ -243,12 +250,20 @@ def __init__(self, lock=None):
 
     def __getstate__(self):
         assert_spawning(self)
-        return (self._lock, self._sleeping_count,
-                self._woken_count, self._wait_semaphore)
+        return (
+            self._lock,
+            self._sleeping_count,
+            self._woken_count,
+            self._wait_semaphore,
+        )
 
     def __setstate__(self, state):
-        (self._lock, self._sleeping_count,
-         self._woken_count, self._wait_semaphore) = state
+        (
+            self._lock,
+            self._sleeping_count,
+            self._woken_count,
+            self._wait_semaphore,
+        ) = state
         self._make_methods()
 
     def __enter__(self):
@@ -263,15 +278,18 @@ def _make_methods(self):
 
     def __repr__(self):
         try:
-            num_waiters = (self._sleeping_count._semlock._get_value() -
-                           self._woken_count._semlock._get_value())
+            num_waiters = (
+                self._sleeping_count._semlock._get_value()
+                - self._woken_count._semlock._get_value()
+            )
         except Exception:
-            num_waiters = 'unknown'
-        return f'<{self.__class__.__name__}({self._lock}, {num_waiters})>'
+            num_waiters = "unknown"
+        return f"<{self.__class__.__name__}({self._lock}, {num_waiters})>"
 
     def wait(self, timeout=None):
-        assert self._lock._semlock._is_mine(), \
-               'must acquire() condition before using wait()'
+        assert (
+            self._lock._semlock._is_mine()
+        ), "must acquire() condition before using wait()"
 
         # indicate that this thread is going to sleep
         self._sleeping_count.release()
@@ -293,7 +311,7 @@ def wait(self, timeout=None):
                 self._lock.acquire()
 
     def notify(self):
-        assert self._lock._semlock._is_mine(), 'lock is not owned'
+        assert self._lock._semlock._is_mine(), "lock is not owned"
         assert not self._wait_semaphore.acquire(False)
 
         # to take account of timeouts since last notify() we subtract
@@ -303,14 +321,14 @@ def notify(self):
             assert res
 
         if self._sleeping_count.acquire(False):  # try grabbing a sleeper
-            self._wait_semaphore.release()       # wake up one sleeper
-            self._woken_count.acquire()          # wait for the sleeper to wake
+            self._wait_semaphore.release()  # wake up one sleeper
+            self._woken_count.acquire()  # wait for the sleeper to wake
 
             # rezero _wait_semaphore in case a timeout just happened
             self._wait_semaphore.acquire(False)
 
     def notify_all(self):
-        assert self._lock._semlock._is_mine(), 'lock is not owned'
+        assert self._lock._semlock._is_mine(), "lock is not owned"
         assert not self._wait_semaphore.acquire(False)
 
         # to take account of timeouts since last notify*() we subtract
@@ -321,12 +339,12 @@ def notify_all(self):
 
         sleepers = 0
         while self._sleeping_count.acquire(False):
-            self._wait_semaphore.release()        # wake up one sleeper
+            self._wait_semaphore.release()  # wake up one sleeper
             sleepers += 1
 
         if sleepers:
             for _ in range(sleepers):
-                self._woken_count.acquire()       # wait for a sleeper to wake
+                self._woken_count.acquire()  # wait for a sleeper to wake
 
             # rezero wait_semaphore in case some timeouts just happened
             while self._wait_semaphore.acquire(False):
@@ -355,8 +373,8 @@ def wait_for(self, predicate, timeout=None):
 # Event
 #
 
-class Event:
 
+class Event:
     def __init__(self):
         self._cond = Condition(Lock())
         self._flag = Semaphore(0)
diff --git a/loky/backend/utils.py b/loky/backend/utils.py
index 2956614e..d38d4dce 100644
--- a/loky/backend/utils.py
+++ b/loky/backend/utils.py
@@ -6,6 +6,7 @@
 import warnings
 import subprocess
 import traceback
+
 try:
     import psutil
 except ImportError:
@@ -93,7 +94,7 @@ def _kill(pid):
     # mandates a SIGTERM signal. While Windows is handled specifically above,
     # let's try to be safe for other hypothetic platforms that only have
     # SIGTERM without SIGKILL.
-    kill_signal = getattr(signal, 'SIGKILL', signal.SIGTERM)
+    kill_signal = getattr(signal, "SIGKILL", signal.SIGTERM)
     try:
         os.kill(pid, kill_signal)
     except OSError as e:
@@ -113,7 +114,7 @@ def _posix_recursive_kill(pid):
     except subprocess.CalledProcessError as e:
         # `ps` returns 1 when no child process has been found
         if e.returncode == 1:
-            children_pids = ''
+            children_pids = ""
         else:
             raise  # pragma: no cover
 
@@ -136,21 +137,26 @@ def get_exitcodes_terminated_worker(processes):
     # Catch the exitcode of the terminated workers. There should at least be
     # one. If not, wait a bit for the system to correctly set the exitcode of
     # the terminated worker.
-    exitcodes = [p.exitcode for p in list(processes.values())
-                 if p.exitcode is not None]
+    exitcodes = [
+        p.exitcode for p in list(processes.values()) if p.exitcode is not None
+    ]
     while not exitcodes and patience > 0:
         patience -= 1
-        exitcodes = [p.exitcode for p in list(processes.values())
-                     if p.exitcode is not None]
-        time.sleep(.05)
+        exitcodes = [
+            p.exitcode
+            for p in list(processes.values())
+            if p.exitcode is not None
+        ]
+        time.sleep(0.05)
 
     return _format_exitcodes(exitcodes)
 
 
 def _format_exitcodes(exitcodes):
     """Format a list of exit code with names of the signals if possible"""
-    str_exitcodes = [f"{_get_exitcode_name(e)}({e})"
-                     for e in exitcodes if e is not None]
+    str_exitcodes = [
+        f"{_get_exitcode_name(e)}({e})" for e in exitcodes if e is not None
+    ]
     return "{" + ", ".join(str_exitcodes) + "}"
 
 
@@ -163,6 +169,7 @@ def _get_exitcode_name(exitcode):
     if exitcode < 0:
         try:
             import signal
+
             return signal.Signals(-exitcode).name
         except ValueError:
             return "UNKNOWN"
diff --git a/loky/cloudpickle_wrapper.py b/loky/cloudpickle_wrapper.py
index 15a09939..165a5240 100644
--- a/loky/cloudpickle_wrapper.py
+++ b/loky/cloudpickle_wrapper.py
@@ -21,14 +21,13 @@ def __reduce__(self):
     def __getattr__(self, attr):
         # Ensure that the wrapped object can be used seemlessly as the
         # previous object.
-        if attr not in ['_obj', '_keep_wrapper']:
+        if attr not in ["_obj", "_keep_wrapper"]:
             return getattr(self._obj, attr)
         return getattr(self, attr)
 
 
 # Make sure the wrapped object conserves the callable property
 class CallableObjectWrapper(CloudpickledObjectWrapper):
-
     def __call__(self, *args, **kwargs):
         return self._obj(*args, **kwargs)
 
@@ -52,8 +51,10 @@ def _wrap_objects_when_needed(obj):
         return partial(
             _wrap_objects_when_needed(obj.func),
             *[_wrap_objects_when_needed(a) for a in obj.args],
-            **{k: _wrap_objects_when_needed(v)
-                for k, v in obj.keywords.items()}
+            **{
+                k: _wrap_objects_when_needed(v)
+                for k, v in obj.keywords.items()
+            }
         )
     if callable(obj):
         # Need wrap if the object is a function defined in a local scope of
@@ -87,6 +88,7 @@ def wrap_non_picklable_objects(obj, keep_wrapper=True):
     # If obj is a  class, create a CloudpickledClassWrapper which instantiates
     # the object internally and wrap it directly in a CloudpickledObjectWrapper
     if inspect.isclass(obj):
+
         class CloudpickledClassWrapper(CloudpickledObjectWrapper):
             def __init__(self, *args, **kwargs):
                 self._obj = obj(*args, **kwargs)
diff --git a/loky/initializers.py b/loky/initializers.py
index cc4b7b17..aea0e56c 100644
--- a/loky/initializers.py
+++ b/loky/initializers.py
@@ -4,6 +4,7 @@
 def _viztracer_init(init_kwargs):
     """Initialize viztracer's profiler in worker processes"""
     from viztracer import VizTracer
+
     tracer = VizTracer(**init_kwargs)
     tracer.register_exit()
     tracer.start()
@@ -12,8 +13,9 @@ def _viztracer_init(init_kwargs):
 def _make_viztracer_initializer_and_initargs():
     try:
         import viztracer
+
         tracer = viztracer.get_tracer()
-        if tracer is not None and getattr(tracer, 'enable', False):
+        if tracer is not None and getattr(tracer, "enable", False):
             # Profiler is active: introspect its configuration to
             # initialize the workers with the same configuration.
             return _viztracer_init, (tracer.init_kwargs,)
@@ -70,7 +72,9 @@ def _prepare_initializer(initializer, initargs):
 
     # Introspect runtime to determine if we need to propagate the viztracer
     # profiler information to the workers:
-    return _chain_initializers([
-        (initializer, initargs),
-        _make_viztracer_initializer_and_initargs(),
-    ])
+    return _chain_initializers(
+        [
+            (initializer, initargs),
+            _make_viztracer_initializer_and_initargs(),
+        ]
+    )
diff --git a/loky/process_executor.py b/loky/process_executor.py
index 60a41bc2..0ba47eb2 100644
--- a/loky/process_executor.py
+++ b/loky/process_executor.py
@@ -55,7 +55,7 @@
 """
 
 
-__author__ = 'Thomas Moreau (thomas.moreau.2010@gmail.com)'
+__author__ = "Thomas Moreau (thomas.moreau.2010@gmail.com)"
 
 
 import os
@@ -93,7 +93,7 @@
 _CURRENT_DEPTH = 0
 
 # Minimum time interval between two consecutive memory leak protection checks.
-_MEMORY_LEAK_CHECK_DELAY = 1.
+_MEMORY_LEAK_CHECK_DELAY = 1.0
 
 # Number of bytes of memory usage allowed over the reference process size.
 _MAX_MEMORY_LEAK_SIZE = int(3e8)
@@ -101,6 +101,7 @@
 
 try:
     from psutil import Process
+
     _USE_PSUTIL = True
 
     def _get_memory_usage(pid, force_gc=False):
@@ -108,7 +109,7 @@ def _get_memory_usage(pid, force_gc=False):
             gc.collect()
 
         mem_size = Process(pid).memory_info().rss
-        mp.util.debug(f'psutil return memory size: {mem_size}')
+        mp.util.debug(f"psutil return memory size: {mem_size}")
         return mem_size
 
 except ImportError:
@@ -143,6 +144,7 @@ class _ExecutorFlags:
     and crash_detection_thread to maintain the pool without preventing the
     garbage collection of unreferenced executors.
     """
+
     def __init__(self, shutdown_lock):
 
         self.shutdown = False
@@ -185,8 +187,10 @@ def _python_exit():
     _global_shutdown = True
     items = list(_threads_wakeups.items())
     if len(items) > 0:
-        mp.util.debug("Interpreter shutting down. Waking up "
-                      f"executor_manager_thread {items}")
+        mp.util.debug(
+            "Interpreter shutting down. Waking up "
+            f"executor_manager_thread {items}"
+        )
     for _, (shutdown_lock, thread_wakeup) in items:
         with shutdown_lock:
             thread_wakeup.wakeup()
@@ -211,8 +215,8 @@ def _python_exit():
 
 
 class _RemoteTraceback(Exception):
-    """Embed stringification of remote traceback in local traceback
-    """
+    """Embed stringification of remote traceback in local traceback"""
+
     def __init__(self, tb=None):
         self.tb = f'\n"""\n{tb}"""'
 
@@ -223,13 +227,12 @@ def __str__(self):
 # Do not inherit from BaseException to mirror
 # concurrent.futures.process._ExceptionWithTraceback
 class _ExceptionWithTraceback:
-
     def __init__(self, exc):
         tb = getattr(exc, "__traceback__", None)
         if tb is None:
             _, _, tb = sys.exc_info()
         tb = traceback.format_exception(type(exc), exc, tb)
-        tb = ''.join(tb)
+        tb = "".join(tb)
         self.exc = exc
         self.tb = tb
 
@@ -254,7 +257,6 @@ def __init__(self, future, fn, args, kwargs):
 
 
 class _ResultItem:
-
     def __init__(self, work_id, exception=None, result=None):
         self.work_id = work_id
         self.exception = exception
@@ -262,7 +264,6 @@ def __init__(self, work_id, exception=None, result=None):
 
 
 class _CallItem:
-
     def __init__(self, work_id, fn, args, kwargs):
         self.work_id = work_id
         self.fn = fn
@@ -284,8 +285,16 @@ def __repr__(self):
 
 class _SafeQueue(Queue):
     """Safe Queue set exception to the future object linked to a job"""
-    def __init__(self, max_size=0, ctx=None, pending_work_items=None,
-                 running_work_items=None, thread_wakeup=None, reducers=None):
+
+    def __init__(
+        self,
+        max_size=0,
+        ctx=None,
+        pending_work_items=None,
+        running_work_items=None,
+        thread_wakeup=None,
+        reducers=None,
+    ):
         self.thread_wakeup = thread_wakeup
         self.pending_work_items = pending_work_items
         self.running_work_items = running_work_items
@@ -297,13 +306,16 @@ def _on_queue_feeder_error(self, e, obj):
             if isinstance(e, struct.error):
                 raised_error = RuntimeError(
                     "The task could not be sent to the workers as it is too "
-                    "large for `send_bytes`.")
+                    "large for `send_bytes`."
+                )
             else:
                 raised_error = PicklingError(
-                    "Could not pickle the task to send it to the workers.")
+                    "Could not pickle the task to send it to the workers."
+                )
             tb = traceback.format_exception(
-                type(e), e, getattr(e, "__traceback__", None))
-            raised_error.__cause__ = _RemoteTraceback(''.join(tb))
+                type(e), e, getattr(e, "__traceback__", None)
+            )
+            raised_error.__cause__ = _RemoteTraceback("".join(tb))
             work_item = self.pending_work_items.pop(obj.work_id, None)
             self.running_work_items.remove(obj.work_id)
             # work_item can be None if another process terminated. In this
@@ -318,7 +330,7 @@ def _on_queue_feeder_error(self, e, obj):
 
 
 def _get_chunks(chunksize, *iterables):
-    """Iterates over zip()ed iterables in chunks. """
+    """Iterates over zip()ed iterables in chunks."""
     it = zip(*iterables)
     while True:
         chunk = tuple(itertools.islice(it, chunksize))
@@ -342,16 +354,24 @@ def _process_chunk(fn, chunk):
 def _sendback_result(result_queue, work_id, result=None, exception=None):
     """Safely send back the given result or exception"""
     try:
-        result_queue.put(_ResultItem(work_id, result=result,
-                                     exception=exception))
+        result_queue.put(
+            _ResultItem(work_id, result=result, exception=exception)
+        )
     except BaseException as e:
         exc = _ExceptionWithTraceback(e)
         result_queue.put(_ResultItem(work_id, exception=exc))
 
 
-def _process_worker(call_queue, result_queue, initializer, initargs,
-                    processes_management_lock, timeout, worker_exit_lock,
-                    current_depth):
+def _process_worker(
+    call_queue,
+    result_queue,
+    initializer,
+    initargs,
+    processes_management_lock,
+    timeout,
+    worker_exit_lock,
+    current_depth,
+):
     """Evaluates calls from call_queue and places the results in result_queue.
 
     This worker is run in a separate process.
@@ -375,7 +395,7 @@ def _process_worker(call_queue, result_queue, initializer, initargs,
         try:
             initializer(*initargs)
         except BaseException:
-            LOGGER.critical('Exception in initializer:', exc_info=True)
+            LOGGER.critical("Exception in initializer:", exc_info=True)
             # The parent will notice that the process stopped and
             # mark the pool broken
             return
@@ -387,7 +407,7 @@ def _process_worker(call_queue, result_queue, initializer, initargs,
     _last_memory_leak_check = None
     pid = os.getpid()
 
-    mp.util.debug(f'Worker started with timeout={timeout}')
+    mp.util.debug(f"Worker started with timeout={timeout}")
     while True:
         try:
             call_item = call_queue.get(block=True, timeout=timeout)
@@ -409,7 +429,7 @@ def _process_worker(call_queue, result_queue, initializer, initargs,
                 # If we cannot format correctly the exception, at least print
                 # the traceback.
                 print(previous_tb)
-            mp.util.debug('Exiting with code 1')
+            mp.util.debug("Exiting with code 1")
             sys.exit(1)
         if call_item is None:
             # Notify queue management thread about worker shutdown
@@ -422,9 +442,9 @@ def _process_worker(call_queue, result_queue, initializer, initargs,
             _python_exit()
 
             if is_clean:
-                mp.util.debug('Exited cleanly')
+                mp.util.debug("Exited cleanly")
             else:
-                mp.util.info('Main process did not release worker_exit')
+                mp.util.info("Main process did not release worker_exit")
             return
         try:
             r = call_item()
@@ -466,14 +486,14 @@ def _process_worker(call_queue, result_queue, initializer, initargs,
                 mp.util.info("Memory leak detected: shutting down worker")
                 result_queue.put(pid)
                 with worker_exit_lock:
-                    mp.util.debug('Exit due to memory leak')
+                    mp.util.debug("Exit due to memory leak")
                     return
         else:
             # if psutil is not installed, trigger gc.collect events
             # regularly to limit potential memory leaks due to reference cycles
-            if (_last_memory_leak_check is None or
-                    (time() - _last_memory_leak_check >
-                     _MEMORY_LEAK_CHECK_DELAY)):
+            if _last_memory_leak_check is None or (
+                time() - _last_memory_leak_check > _MEMORY_LEAK_CHECK_DELAY
+            ):
                 gc.collect()
                 _last_memory_leak_check = time()
 
@@ -505,15 +525,19 @@ def __init__(self, executor):
         # When the executor gets garbage collected, the weakref callback
         # will wake up the queue management thread so that it can terminate
         # if there is no pending work item.
-        def weakref_cb(_,
-                       thread_wakeup=self.thread_wakeup,
-                       shutdown_lock=self.shutdown_lock):
+        def weakref_cb(
+            _,
+            thread_wakeup=self.thread_wakeup,
+            shutdown_lock=self.shutdown_lock,
+        ):
             if mp is not None:
                 # At this point, the multiprocessing module can already be
                 # garbage collected. We only log debug info when still
                 # possible.
-                mp.util.debug('Executor collected: triggering callback for'
-                              ' QueueManager wakeup')
+                mp.util.debug(
+                    "Executor collected: triggering callback for"
+                    " QueueManager wakeup"
+                )
             with shutdown_lock:
                 thread_wakeup.wakeup()
 
@@ -591,11 +615,15 @@ def add_call_item_to_queue(self):
 
                 if work_item.future.set_running_or_notify_cancel():
                     self.running_work_items += [work_id]
-                    self.call_queue.put(_CallItem(work_id,
-                                                  work_item.fn,
-                                                  work_item.args,
-                                                  work_item.kwargs),
-                                        block=True)
+                    self.call_queue.put(
+                        _CallItem(
+                            work_id,
+                            work_item.fn,
+                            work_item.args,
+                            work_item.kwargs,
+                        ),
+                        block=True,
+                    )
                 else:
                     del self.pending_work_items[work_id]
                     continue
@@ -633,8 +661,9 @@ def wait_result_broken_or_wakeup(self):
                     "picklable."
                 )
                 tb = traceback.format_exception(
-                    type(e), e, getattr(e, "__traceback__", None))
-                bpe.__cause__ = _RemoteTraceback(''.join(tb))
+                    type(e), e, getattr(e, "__traceback__", None)
+                )
+                bpe.__cause__ = _RemoteTraceback("".join(tb))
 
         elif wakeup_reader in ready:
             # This is simply a wake-up event that might either trigger putting
@@ -643,7 +672,7 @@ def wait_result_broken_or_wakeup(self):
         else:
             # A worker has terminated and we don't know why, set the state of
             # the executor as broken
-            exit_codes = ''
+            exit_codes = ""
             if sys.platform != "win32":
                 # In Windows, introspecting terminated workers exitcodes seems
                 # unstable, therefore they are not appended in the exception
@@ -652,11 +681,17 @@ def wait_result_broken_or_wakeup(self):
                     "\nThe exit codes of the workers are "
                     f"{get_exitcodes_terminated_worker(self.processes)}"
                 )
-            mp.util.debug('A worker unexpectedly terminated. Workers that '
-                          'might have caused the breakage: '
-                          + str({p.name: p.exitcode
-                                 for p in list(self.processes.values())
-                                 if p is not None and p.sentinel in ready}))
+            mp.util.debug(
+                "A worker unexpectedly terminated. Workers that "
+                "might have caused the breakage: "
+                + str(
+                    {
+                        p.name: p.exitcode
+                        for p in list(self.processes.values())
+                        if p is not None and p.sentinel in ready
+                    }
+                )
+            )
             bpe = TerminatedWorkerError(
                 "A worker process managed by the executor was unexpectedly "
                 "terminated. This could be caused by a segmentation fault "
@@ -695,14 +730,17 @@ def process_result_item(self, result_item):
             # start a new Process and raise a warning.
             n_pending = len(self.pending_work_items)
             n_running = len(self.running_work_items)
-            if (n_pending - n_running > 0 or n_running > len(self.processes)):
+            if n_pending - n_running > 0 or n_running > len(self.processes):
                 executor = self.executor_reference()
-                if (executor is not None
-                        and len(self.processes) < executor._max_workers):
+                if (
+                    executor is not None
+                    and len(self.processes) < executor._max_workers
+                ):
                     warnings.warn(
                         "A worker stopped while some jobs were given to the "
                         "executor. This can be caused by a too short worker "
-                        "timeout or by a memory leak.", UserWarning
+                        "timeout or by a memory leak.",
+                        UserWarning,
                     )
                     with executor._processes_management_lock:
                         executor._adjust_process_count()
@@ -727,9 +765,10 @@ def is_shutting_down(self):
         #        * The executor that owns this worker has been collected OR
         #        * The executor that owns this worker has been shutdown.
         # If the executor is broken, it should be detected in the next loop.
-        return (_global_shutdown or
-                ((executor is None or self.executor_flags.shutdown)
-                 and not self.executor_flags.broken))
+        return _global_shutdown or (
+            (executor is None or self.executor_flags.shutdown)
+            and not self.executor_flags.broken
+        )
 
     def terminate_broken(self, bpe):
         # Terminate the executor because it is in a broken state. The bpe
@@ -762,15 +801,18 @@ def flag_executor_shutting_down(self):
         if self.executor_flags.kill_workers:
             while self.pending_work_items:
                 _, work_item = self.pending_work_items.popitem()
-                work_item.future.set_exception(ShutdownExecutorError(
-                    "The Executor was shutdown with `kill_workers=True` "
-                    "before this job could complete."))
+                work_item.future.set_exception(
+                    ShutdownExecutorError(
+                        "The Executor was shutdown with `kill_workers=True` "
+                        "before this job could complete."
+                    )
+                )
                 del work_item
 
             # Kill the remaining worker forcibly to no waste time joining them
             self.kill_workers(reason="executor shutting down")
 
-    def kill_workers(self, reason=''):
+    def kill_workers(self, reason=""):
         # Terminate the remaining workers using SIGKILL. This function also
         # terminates descendant workers of the children in case there is some
         # nested parallelism.
@@ -803,8 +845,10 @@ def shutdown_workers(self):
         # Full queue when all workers have already been shutdown.
         n_sentinels_sent = 0
         cooldown_time = 0.001
-        while (n_sentinels_sent < n_children_to_stop
-                and self.get_n_children_alive() > 0):
+        while (
+            n_sentinels_sent < n_children_to_stop
+            and self.get_n_children_alive() > 0
+        ):
             for _ in range(n_children_to_stop - n_sentinels_sent):
                 try:
                     self.call_queue.put_nowait(None)
@@ -915,18 +959,19 @@ def _check_max_depth(context):
         raise LokyRecursionError(
             "Could not spawn extra nested processes at depth superior to "
             "MAX_DEPTH=1. It is not possible to increase this limit when "
-            "using the 'fork' start method.")
+            "using the 'fork' start method."
+        )
 
     if 0 < MAX_DEPTH and _CURRENT_DEPTH + 1 > MAX_DEPTH:
         raise LokyRecursionError(
             "Could not spawn extra nested processes at depth superior to "
             f"MAX_DEPTH={MAX_DEPTH}. If this is intendend, you can change "
-            "this limit with the LOKY_MAX_DEPTH environment variable.")
+            "this limit with the LOKY_MAX_DEPTH environment variable."
+        )
 
 
 class LokyRecursionError(RuntimeError):
-    """Raised when a process try to spawn too many levels of nested processes.
-    """
+    """Raised when a process try to spawn too many levels of nested processes."""
 
 
 class BrokenProcessPool(_BPPException):
@@ -962,9 +1007,17 @@ class ProcessPoolExecutor(Executor):
 
     _at_exit = None
 
-    def __init__(self, max_workers=None, job_reducers=None,
-                 result_reducers=None, timeout=None, context=None,
-                 initializer=None, initargs=(), env=None):
+    def __init__(
+        self,
+        max_workers=None,
+        job_reducers=None,
+        result_reducers=None,
+        timeout=None,
+        context=None,
+        initializer=None,
+        initargs=(),
+        env=None,
+    ):
         """Initializes a new ProcessPoolExecutor instance.
 
         Args:
@@ -1047,7 +1100,7 @@ def __init__(self, max_workers=None, job_reducers=None,
         # Finally setup the queues for interprocess communication
         self._setup_queues(job_reducers, result_reducers)
 
-        mp.util.debug('ProcessPoolExecutor is setup')
+        mp.util.debug("ProcessPoolExecutor is setup")
 
     def _setup_queues(self, job_reducers, result_reducers, queue_size=None):
         # Make the call queue slightly larger than the number of processes to
@@ -1056,21 +1109,25 @@ def _setup_queues(self, job_reducers, result_reducers, queue_size=None):
         if queue_size is None:
             queue_size = 2 * self._max_workers + EXTRA_QUEUED_CALLS
         self._call_queue = _SafeQueue(
-            max_size=queue_size, pending_work_items=self._pending_work_items,
+            max_size=queue_size,
+            pending_work_items=self._pending_work_items,
             running_work_items=self._running_work_items,
             thread_wakeup=self._executor_manager_thread_wakeup,
-            reducers=job_reducers, ctx=self._context)
+            reducers=job_reducers,
+            ctx=self._context,
+        )
         # Killed worker processes can produce spurious "broken pipe"
         # tracebacks in the queue's own worker thread. But we detect killed
         # processes anyway, so silence the tracebacks.
         self._call_queue._ignore_epipe = True
 
-        self._result_queue = SimpleQueue(reducers=result_reducers,
-                                         ctx=self._context)
+        self._result_queue = SimpleQueue(
+            reducers=result_reducers, ctx=self._context
+        )
 
     def _start_executor_manager_thread(self):
         if self._executor_manager_thread is None:
-            mp.util.debug('_start_executor_manager_thread called')
+            mp.util.debug("_start_executor_manager_thread called")
 
             # Start the processes so that their sentinels are known.
             self._executor_manager_thread = _ExecutorManagerThread(self)
@@ -1078,9 +1135,10 @@ def _start_executor_manager_thread(self):
 
             # register this executor in a mechanism that ensures it will wakeup
             # when the interpreter is exiting.
-            _threads_wakeups[self._executor_manager_thread] = \
-                (self._shutdown_lock,
-                 self._executor_manager_thread_wakeup)
+            _threads_wakeups[self._executor_manager_thread] = (
+                self._shutdown_lock,
+                self._executor_manager_thread_wakeup,
+            )
 
             global process_pool_executor_at_exit
             if process_pool_executor_at_exit is None:
@@ -1090,23 +1148,33 @@ def _start_executor_manager_thread(self):
 
                 if sys.version_info < (3, 9):
                     process_pool_executor_at_exit = mp.util.Finalize(
-                        None, _python_exit, exitpriority=20)
+                        None, _python_exit, exitpriority=20
+                    )
                 else:
                     process_pool_executor_at_exit = threading._register_atexit(
-                        _python_exit)
+                        _python_exit
+                    )
 
     def _adjust_process_count(self):
         while len(self._processes) < self._max_workers:
             worker_exit_lock = self._context.BoundedSemaphore(1)
-            args = (self._call_queue, self._result_queue, self._initializer,
-                    self._initargs, self._processes_management_lock,
-                    self._timeout, worker_exit_lock, _CURRENT_DEPTH + 1)
+            args = (
+                self._call_queue,
+                self._result_queue,
+                self._initializer,
+                self._initargs,
+                self._processes_management_lock,
+                self._timeout,
+                worker_exit_lock,
+                _CURRENT_DEPTH + 1,
+            )
             worker_exit_lock.acquire()
             try:
                 # Try to spawn the process with some environment variable to
                 # overwrite but it only works with the loky context for now.
-                p = self._context.Process(target=_process_worker, args=args,
-                                          env=self._env)
+                p = self._context.Process(
+                    target=_process_worker, args=args, env=self._env
+                )
             except TypeError:
                 p = self._context.Process(target=_process_worker, args=args)
             p._worker_exit_lock = worker_exit_lock
@@ -1118,8 +1186,7 @@ def _adjust_process_count(self):
         )
 
     def _ensure_executor_running(self):
-        """ensures all workers and management thread are running
-        """
+        """ensures all workers and management thread are running"""
         with self._processes_management_lock:
             if len(self._processes) != self._max_workers:
                 self._adjust_process_count()
@@ -1131,13 +1198,15 @@ def submit(self, fn, *args, **kwargs):
                 raise self._flags.broken
             if self._flags.shutdown:
                 raise ShutdownExecutorError(
-                    'cannot schedule new futures after shutdown')
+                    "cannot schedule new futures after shutdown"
+                )
 
             # Cannot submit a new calls once the interpreter is shutting down.
             # This check avoids spawning new processes at exit.
             if _global_shutdown:
-                raise RuntimeError('cannot schedule new futures after '
-                                   'interpreter shutdown')
+                raise RuntimeError(
+                    "cannot schedule new futures after " "interpreter shutdown"
+                )
 
             f = Future()
             w = _WorkItem(f, fn, args, kwargs)
@@ -1150,6 +1219,7 @@ def submit(self, fn, *args, **kwargs):
 
             self._ensure_executor_running()
             return f
+
     submit.__doc__ = Executor.submit.__doc__
 
     def map(self, fn, *iterables, **kwargs):
@@ -1174,19 +1244,20 @@ def map(self, fn, *iterables, **kwargs):
                 before the given timeout.
             Exception: If fn(*args) raises for any values.
         """
-        timeout = kwargs.get('timeout', None)
-        chunksize = kwargs.get('chunksize', 1)
+        timeout = kwargs.get("timeout", None)
+        chunksize = kwargs.get("chunksize", 1)
         if chunksize < 1:
             raise ValueError("chunksize must be >= 1.")
 
         results = super().map(
-            partial(_process_chunk, fn), _get_chunks(chunksize, *iterables),
-            timeout=timeout
+            partial(_process_chunk, fn),
+            _get_chunks(chunksize, *iterables),
+            timeout=timeout,
         )
         return _chain_from_iterable_of_lists(results)
 
     def shutdown(self, wait=True, kill_workers=False):
-        mp.util.debug(f'shutting down executor {self}')
+        mp.util.debug(f"shutting down executor {self}")
 
         self._flags.flag_as_shutting_down(kill_workers)
         executor_manager_thread = self._executor_manager_thread
diff --git a/loky/reusable_executor.py b/loky/reusable_executor.py
index c2c54bc4..189aa1ea 100644
--- a/loky/reusable_executor.py
+++ b/loky/reusable_executor.py
@@ -12,7 +12,7 @@
 from .backend.context import cpu_count
 from .backend import get_context
 
-__all__ = ['get_reusable_executor']
+__all__ = ["get_reusable_executor"]
 
 # Singleton executor and id management
 _executor_lock = threading.RLock()
@@ -34,10 +34,18 @@ def _get_next_executor_id():
         return executor_id
 
 
-def get_reusable_executor(max_workers=None, context=None, timeout=10,
-                          kill_workers=False, reuse="auto",
-                          job_reducers=None, result_reducers=None,
-                          initializer=None, initargs=(), env=None):
+def get_reusable_executor(
+    max_workers=None,
+    context=None,
+    timeout=10,
+    kill_workers=False,
+    reuse="auto",
+    job_reducers=None,
+    result_reducers=None,
+    initializer=None,
+    initargs=(),
+    env=None,
+):
     """Return the current ReusableExectutor instance.
 
     Start a new instance if it has not been started already or if the previous
@@ -79,31 +87,61 @@ def get_reusable_executor(max_workers=None, context=None, timeout=10,
     ``loky`` context.
     """
     _executor, _ = _ReusablePoolExecutor.get_reusable_executor(
-        max_workers=max_workers, context=context, timeout=timeout,
-        kill_workers=kill_workers, reuse=reuse, job_reducers=job_reducers,
-        result_reducers=result_reducers, initializer=initializer,
-        initargs=initargs, env=env
+        max_workers=max_workers,
+        context=context,
+        timeout=timeout,
+        kill_workers=kill_workers,
+        reuse=reuse,
+        job_reducers=job_reducers,
+        result_reducers=result_reducers,
+        initializer=initializer,
+        initargs=initargs,
+        env=env,
     )
     return _executor
 
 
 class _ReusablePoolExecutor(ProcessPoolExecutor):
-    def __init__(self, submit_resize_lock, max_workers=None, context=None,
-                 timeout=None, executor_id=0, job_reducers=None,
-                 result_reducers=None, initializer=None, initargs=(),
-                 env=None):
+    def __init__(
+        self,
+        submit_resize_lock,
+        max_workers=None,
+        context=None,
+        timeout=None,
+        executor_id=0,
+        job_reducers=None,
+        result_reducers=None,
+        initializer=None,
+        initargs=(),
+        env=None,
+    ):
         super().__init__(
-            max_workers=max_workers, context=context, timeout=timeout,
-            job_reducers=job_reducers, result_reducers=result_reducers,
-            initializer=initializer, initargs=initargs, env=env)
+            max_workers=max_workers,
+            context=context,
+            timeout=timeout,
+            job_reducers=job_reducers,
+            result_reducers=result_reducers,
+            initializer=initializer,
+            initargs=initargs,
+            env=env,
+        )
         self.executor_id = executor_id
         self._submit_resize_lock = submit_resize_lock
 
     @classmethod
-    def get_reusable_executor(cls, max_workers=None, context=None, timeout=10,
-                              kill_workers=False, reuse="auto",
-                              job_reducers=None, result_reducers=None,
-                              initializer=None, initargs=(), env=None):
+    def get_reusable_executor(
+        cls,
+        max_workers=None,
+        context=None,
+        timeout=10,
+        kill_workers=False,
+        reuse="auto",
+        job_reducers=None,
+        result_reducers=None,
+        initializer=None,
+        initargs=(),
+        env=None,
+    ):
         with _executor_lock:
             global _executor, _executor_kwargs
             executor = _executor
@@ -125,11 +163,15 @@ def get_reusable_executor(cls, max_workers=None, context=None, timeout=10,
                     "Cannot use reusable executor with the 'fork' context"
                 )
 
-            kwargs = dict(context=context, timeout=timeout,
-                          job_reducers=job_reducers,
-                          result_reducers=result_reducers,
-                          initializer=initializer, initargs=initargs,
-                          env=env)
+            kwargs = dict(
+                context=context,
+                timeout=timeout,
+                job_reducers=job_reducers,
+                result_reducers=result_reducers,
+                initializer=initializer,
+                initargs=initargs,
+                env=env,
+            )
             if executor is None:
                 is_reused = False
                 mp.util.debug(
@@ -138,13 +180,19 @@ def get_reusable_executor(cls, max_workers=None, context=None, timeout=10,
                 executor_id = _get_next_executor_id()
                 _executor_kwargs = kwargs
                 _executor = executor = cls(
-                    _executor_lock, max_workers=max_workers,
-                    executor_id=executor_id, **kwargs)
+                    _executor_lock,
+                    max_workers=max_workers,
+                    executor_id=executor_id,
+                    **kwargs,
+                )
             else:
-                if reuse == 'auto':
+                if reuse == "auto":
                     reuse = kwargs == _executor_kwargs
-                if (executor._flags.broken or executor._flags.shutdown
-                        or not reuse):
+                if (
+                    executor._flags.broken
+                    or executor._flags.shutdown
+                    or not reuse
+                ):
                     if executor._flags.broken:
                         reason = "broken"
                     elif executor._flags.shutdown:
@@ -159,8 +207,9 @@ def get_reusable_executor(cls, max_workers=None, context=None, timeout=10,
                     executor.shutdown(wait=True, kill_workers=kill_workers)
                     _executor = executor = _executor_kwargs = None
                     # Recursive call to build a new instance
-                    return cls.get_reusable_executor(max_workers=max_workers,
-                                                     **kwargs)
+                    return cls.get_reusable_executor(
+                        max_workers=max_workers, **kwargs
+                    )
                 else:
                     mp.util.debug(
                         "Reusing existing executor with "
@@ -200,8 +249,9 @@ def _resize(self, max_workers):
                 self._max_workers = max_workers
                 for _ in range(max_workers, nb_children_alive):
                     self._call_queue.put(None)
-            while (len(self._processes) > max_workers
-                   and not self._flags.broken):
+            while (
+                len(self._processes) > max_workers and not self._flags.broken
+            ):
                 time.sleep(1e-3)
 
             self._adjust_process_count()
@@ -213,9 +263,11 @@ def _wait_job_completion(self):
         """Wait for the cache to be empty before resizing the pool."""
         # Issue a warning to the user about the bad effect of this usage.
         if self._pending_work_items:
-            warnings.warn("Trying to resize an executor with running jobs: "
-                          "waiting for jobs completion before resizing.",
-                          UserWarning)
+            warnings.warn(
+                "Trying to resize an executor with running jobs: "
+                "waiting for jobs completion before resizing.",
+                UserWarning,
+            )
             mp.util.debug(
                 f"Executor {self.executor_id} waiting for jobs completion "
                 "before resizing"
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 00000000..dfab0250
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,16 @@
+[tool.black]
+line-length = 79
+include = '\.pyi?$'
+exclude = '''
+/(
+    \.git
+  | \.hg
+  | \.mypy_cache
+  | \.tox
+  | \.venv
+  | _build
+  | buck-out
+  | build
+  | dist
+)/
+'''
diff --git a/setup.py b/setup.py
index 703b6703..79e76ac6 100644
--- a/setup.py
+++ b/setup.py
@@ -4,16 +4,17 @@
 from setuptools import setup, find_packages
 from distutils.command.clean import clean as Clean
 
-packages = find_packages(exclude=['tests', 'tests._openmp', 'benchmark'])
+packages = find_packages(exclude=["tests", "tests._openmp", "benchmark"])
 
 
 # Function to parse __version__ in `loky`
 def find_version():
     here = os.path.abspath(os.path.dirname(__file__))
-    with open(os.path.join(here, 'loky', '__init__.py')) as fp:
+    with open(os.path.join(here, "loky", "__init__.py")) as fp:
         version_file = fp.read()
-    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
-                              version_file, re.M)
+    version_match = re.search(
+        r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M
+    )
     if version_match:
         return version_match.group(1)
     raise RuntimeError("Unable to find version string.")
@@ -27,61 +28,64 @@ def run(self):
         Clean.run(self)
         # Remove c files if we are not within a sdist package
         cwd = os.path.abspath(os.path.dirname(__file__))
-        remove_c_files = not os.path.exists(os.path.join(cwd, 'PKG-INFO'))
+        remove_c_files = not os.path.exists(os.path.join(cwd, "PKG-INFO"))
         if remove_c_files:
-            print('Will remove generated .c files')
-        if os.path.exists('build'):
-            shutil.rmtree('build')
-        for dirpath, dirnames, filenames in os.walk('.'):
+            print("Will remove generated .c files")
+        if os.path.exists("build"):
+            shutil.rmtree("build")
+        for dirpath, dirnames, filenames in os.walk("."):
             for filename in filenames:
-                if any(filename.endswith(suffix) for suffix in
-                       (".so", ".pyd", ".dll", ".pyc")):
+                if any(
+                    filename.endswith(suffix)
+                    for suffix in (".so", ".pyd", ".dll", ".pyc")
+                ):
                     os.unlink(os.path.join(dirpath, filename))
                     continue
                 extension = os.path.splitext(filename)[1]
-                if remove_c_files and extension in ['.c', '.cpp']:
-                    pyx_file = str.replace(filename, extension, '.pyx')
+                if remove_c_files and extension in [".c", ".cpp"]:
+                    pyx_file = str.replace(filename, extension, ".pyx")
                     if os.path.exists(os.path.join(dirpath, pyx_file)):
                         os.unlink(os.path.join(dirpath, filename))
             for dirname in dirnames:
-                if dirname == '__pycache__':
+                if dirname == "__pycache__":
                     shutil.rmtree(os.path.join(dirpath, dirname))
 
 
-cmdclass = {'clean': CleanCommand}
+cmdclass = {"clean": CleanCommand}
 
 setup(
-    name='loky',
+    name="loky",
     version=find_version(),
-    description=("A robust implementation of "
-                 "concurrent.futures.ProcessPoolExecutor"),
-    long_description=open('README.md').read(),
-    long_description_content_type='text/markdown',
-    url='https://github.com/joblib/loky/',
-    author='Thomas Moreau',
-    author_email='thomas.moreau.2010@gmail.com',
+    description=(
+        "A robust implementation of " "concurrent.futures.ProcessPoolExecutor"
+    ),
+    long_description=open("README.md").read(),
+    long_description_content_type="text/markdown",
+    url="https://github.com/joblib/loky/",
+    author="Thomas Moreau",
+    author_email="thomas.moreau.2010@gmail.com",
     packages=packages,
     zip_safe=False,
-    license='BSD',
+    license="BSD",
     classifiers=[
-        'Development Status :: 5 - Production/Stable',
-        'Environment :: Console',
-        'Intended Audience :: Developers',
-        'Intended Audience :: Science/Research',
-        'License :: OSI Approved :: BSD License',
-        'Operating System :: OS Independent',
-        'Programming Language :: Python :: 3',
-        'Programming Language :: Python :: 3.7',
-        'Programming Language :: Python :: 3.8',
-        'Programming Language :: Python :: 3.9',
-        'Programming Language :: Python :: 3.10',
-        'Topic :: Scientific/Engineering',
-        'Topic :: Utilities',
-        'Topic :: Software Development :: Libraries',
+        "Development Status :: 5 - Production/Stable",
+        "Environment :: Console",
+        "Intended Audience :: Developers",
+        "Intended Audience :: Science/Research",
+        "License :: OSI Approved :: BSD License",
+        "Operating System :: OS Independent",
+        "Programming Language :: Python :: 3",
+        "Programming Language :: Python :: 3.7",
+        "Programming Language :: Python :: 3.8",
+        "Programming Language :: Python :: 3.9",
+        "Programming Language :: Python :: 3.10",
+        "Topic :: Scientific/Engineering",
+        "Topic :: Utilities",
+        "Topic :: Software Development :: Libraries",
     ],
     cmdclass=cmdclass,
-    platforms='any',
-    python_requires='>=3.7',
-    install_requires=['cloudpickle'],
-    tests_require=['packaging', 'pytest', 'psutil'],
+    platforms="any",
+    python_requires=">=3.7",
+    install_requires=["cloudpickle"],
+    tests_require=["packaging", "pytest", "psutil"],
 )


Test patch:
diff --git a/tests/_executor_mixin.py b/tests/_executor_mixin.py
index 9d949905..7dbf7acf 100644
--- a/tests/_executor_mixin.py
+++ b/tests/_executor_mixin.py
@@ -11,6 +11,7 @@
 
 try:
     import psutil
+
     psutil_exceptions = (psutil.NoSuchProcess, psutil.AccessDenied)
 except ImportError:
     psutil = None
@@ -54,20 +55,32 @@ def _direct_children_with_cmdline(p):
 
 def _running_children_pids_with_cmdline(p):
     all_children = _direct_children_with_cmdline(p)
-    workers = [(c, cmdline) for c, cmdline in all_children
-               if ('semaphore_tracker' not in cmdline and
-                   'resource_tracker' not in cmdline and
-                   'multiprocessing.forkserver' not in cmdline)]
+    workers = [
+        (c, cmdline)
+        for c, cmdline in all_children
+        if (
+            "semaphore_tracker" not in cmdline
+            and "resource_tracker" not in cmdline
+            and "multiprocessing.forkserver" not in cmdline
+        )
+    ]
 
-    forkservers = [c for c, cmdline in all_children
-                   if 'multiprocessing.forkserver' in cmdline]
+    forkservers = [
+        c
+        for c, cmdline in all_children
+        if "multiprocessing.forkserver" in cmdline
+    ]
     for fs in forkservers:
         workers += _direct_children_with_cmdline(fs)
     return [(w.pid, cmdline) for w, cmdline in workers]
 
 
-def _check_subprocesses_number(executor=None, expected_process_number=None,
-                               expected_max_process_number=None, patience=10):
+def _check_subprocesses_number(
+    executor=None,
+    expected_process_number=None,
+    expected_max_process_number=None,
+    patience=10,
+):
     if not psutil:
         # psutil is not installed, we cannot check the number of subprocesses
         return
@@ -75,7 +88,9 @@ def _check_subprocesses_number(executor=None, expected_process_number=None,
     for trial_idx in range(patience):
         try:
             # Wait for terminating processes to disappear
-            pids_cmdlines = _running_children_pids_with_cmdline(psutil.Process())
+            pids_cmdlines = _running_children_pids_with_cmdline(
+                psutil.Process()
+            )
             children_pids = {pid for pid, _ in pids_cmdlines}
             if executor is not None:
                 worker_pids = set(executor._processes.keys())
@@ -85,12 +100,20 @@ def _check_subprocesses_number(executor=None, expected_process_number=None,
                 # Bypass pids checks when executor has been garbage collected
                 worker_pids = children_pids
             if expected_process_number is not None:
-                assert len(children_pids) == expected_process_number, pids_cmdlines
-                assert len(worker_pids) == expected_process_number, pids_cmdlines
+                assert (
+                    len(children_pids) == expected_process_number
+                ), pids_cmdlines
+                assert (
+                    len(worker_pids) == expected_process_number
+                ), pids_cmdlines
 
             if expected_max_process_number is not None:
-                assert len(children_pids) <= expected_max_process_number, pids_cmdlines
-                assert len(worker_pids) <= expected_max_process_number, pids_cmdlines
+                assert (
+                    len(children_pids) <= expected_max_process_number
+                ), pids_cmdlines
+                assert (
+                    len(worker_pids) <= expected_max_process_number
+                ), pids_cmdlines
 
             return
         except AssertionError as e:
@@ -109,11 +132,16 @@ def _check_executor_started(executor):
     try:
         res.result(timeout=TIMEOUT)
     except TimeoutError:
-        print('\n' * 3, res.done(), executor._call_queue.empty(),
-              executor._result_queue.empty())
+        print(
+            "\n" * 3,
+            res.done(),
+            executor._call_queue.empty(),
+            executor._result_queue.empty(),
+        )
         print(executor._processes)
         print(threading.enumerate())
         from faulthandler import dump_traceback
+
         dump_traceback()
         executor.submit(dump_traceback).result(TIMEOUT)
         raise RuntimeError("Executor took too long to run basic task.")
@@ -144,8 +172,11 @@ def setup_method(self):
         assert _test_event is not None
         try:
             self.executor = self.executor_type(
-                max_workers=self.worker_count, context=self.context,
-                initializer=initializer_event, initargs=(_test_event,))
+                max_workers=self.worker_count,
+                context=self.context,
+                initializer=initializer_event,
+                initargs=(_test_event,),
+            )
         except NotImplementedError as e:
             self.skipTest(str(e))
         _check_executor_started(self.executor)
@@ -153,7 +184,7 @@ def setup_method(self):
 
     def teardown_method(self, method):
         # Make sure executor is not broken if it should not be
-        executor = getattr(self, 'executor', None)
+        executor = getattr(self, "executor", None)
         if executor is not None:
             try:
                 # old pytest markers:
@@ -194,8 +225,10 @@ def teardown_method(self, method):
     def _prime_executor(self):
         # Make sure that the executor is ready to do work before running the
         # tests. This should reduce the probability of timeouts in the tests.
-        futures = [self.executor.submit(time.sleep, 0.1)
-                   for _ in range(self.worker_count)]
+        futures = [
+            self.executor.submit(time.sleep, 0.1)
+            for _ in range(self.worker_count)
+        ]
         for f in futures:
             f.result()
 
@@ -217,16 +250,15 @@ def check_no_running_workers(cls, patience=5, sleep_duration=0.01):
         # raise error.
         print("Remaining worker processes command lines:", file=sys.stderr)
         for w, cmdline in workers:
-            print(w.pid, w.status(), end='\n', file=sys.stderr)
-            print(cmdline, end='\n\n', file=sys.stderr)
+            print(w.pid, w.status(), end="\n", file=sys.stderr)
+            print(cmdline, end="\n\n", file=sys.stderr)
         raise AssertionError(
-            f'Expected no more running worker processes but got {len(workers)}'
-            f' after waiting {patience:0.3f}s.'
+            f"Expected no more running worker processes but got {len(workers)}"
+            f" after waiting {patience:0.3f}s."
         )
 
 
 class ReusableExecutorMixin:
-
     def setup_method(self, method):
         default_start_method = get_context().get_start_method()
         assert default_start_method == "loky", default_start_method
@@ -237,7 +269,9 @@ def setup_method(self, method):
 
         # Check that there no other running subprocesses beyond the workers
         # of the reusable executor.
-        _check_subprocesses_number(executor=None, expected_max_process_number=2)
+        _check_subprocesses_number(
+            executor=None, expected_max_process_number=2
+        )
 
     def teardown_method(self, method):
         """Make sure the executor can be recovered after the tests"""
@@ -248,7 +282,9 @@ def teardown_method(self, method):
 
         # Check that there no other running subprocesses beyond the workers
         # of the reusable executor.
-        _check_subprocesses_number(executor=None, expected_max_process_number=2)
+        _check_subprocesses_number(
+            executor=None, expected_max_process_number=2
+        )
 
     @classmethod
     def teardown_class(cls):
diff --git a/tests/_openmp/_fail_fork.py b/tests/_openmp/_fail_fork.py
index 22261889..97d761a8 100644
--- a/tests/_openmp/_fail_fork.py
+++ b/tests/_openmp/_fail_fork.py
@@ -4,11 +4,16 @@
 from openmp_parallel_sum import parallel_sum
 
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     import argparse
-    parser = argparse.ArgumentParser('Test compat openMP/multproc')
-    parser.add_argument('--start', type=str, default='fork',
-                        help='define start method tested with openMP')
+
+    parser = argparse.ArgumentParser("Test compat openMP/multproc")
+    parser.add_argument(
+        "--start",
+        type=str,
+        default="fork",
+        help="define start method tested with openMP",
+    )
     args = parser.parse_args()
 
     parallel_sum(10)
diff --git a/tests/_openmp/setup.py b/tests/_openmp/setup.py
index a460af4d..63273d99 100644
--- a/tests/_openmp/setup.py
+++ b/tests/_openmp/setup.py
@@ -11,7 +11,7 @@
 
 if sys.platform != "win32":
     extra_compile_args = ["-ffast-math", "-fopenmp"]
-    extra_link_args = ['-fopenmp']
+    extra_link_args = ["-fopenmp"]
 else:
     extra_compile_args = ["/openmp"]
     extra_link_args = None
@@ -21,11 +21,11 @@
         "parallel_sum",
         ["parallel_sum.pyx"],
         extra_compile_args=extra_compile_args,
-        extra_link_args=extra_link_args
-        )
+        extra_link_args=extra_link_args,
+    )
 ]
 
 setup(
-    name='_openmp',
+    name="_openmp",
     ext_modules=cythonize(ext_modules),
 )
diff --git a/tests/_test_process_executor.py b/tests/_test_process_executor.py
index 20c017b5..f58af9f8 100644
--- a/tests/_test_process_executor.py
+++ b/tests/_test_process_executor.py
@@ -18,8 +18,13 @@
 from threading import Thread
 from collections import defaultdict
 from concurrent import futures
-from concurrent.futures._base import (PENDING, RUNNING, CANCELLED,
-                                      CANCELLED_AND_NOTIFIED, FINISHED)
+from concurrent.futures._base import (
+    PENDING,
+    RUNNING,
+    CANCELLED,
+    CANCELLED_AND_NOTIFIED,
+    FINISHED,
+)
 
 import loky
 from loky.process_executor import (
@@ -70,7 +75,7 @@ def sleep_and_return(delay, x):
 
 def sleep_and_write(t, filename, msg):
     time.sleep(t)
-    with open(filename, 'w') as f:
+    with open(filename, "w") as f:
         f.write(str(msg))
 
 
@@ -98,7 +103,6 @@ def _assert_no_error(stderr):
 
 
 class ExecutorShutdownTest:
-
     def test_run_after_shutdown(self):
         self.executor.shutdown()
         with pytest.raises(RuntimeError):
@@ -120,7 +124,7 @@ def test_interpreter_shutdown(self):
 
         executor_type = self.executor_type.__name__
         start_method = self.context.get_start_method()
-        tempdir = tempfile.mkdtemp(prefix='loky_').replace("\\", "/")
+        tempdir = tempfile.mkdtemp(prefix="loky_").replace("\\", "/")
         try:
             n_jobs = 4
             code = f"""if True:
@@ -143,14 +147,16 @@ def test_interpreter_shutdown(self):
                 # processes finish in the background.
             """
             _, stderr = check_subprocess_call(
-                [sys.executable, "-c", code], timeout=55)
+                [sys.executable, "-c", code], timeout=55
+            )
 
             _assert_no_error(stderr)
 
             # The workers should have completed their work before the main
             # process exits:
-            expected_filenames = [f'task_{i:02d}.log'
-                                  for i in range(2 * n_jobs)]
+            expected_filenames = [
+                f"task_{i:02d}.log" for i in range(2 * n_jobs)
+            ]
 
             # Apparently files can take some time to appear under windows
             # on AppVeyor
@@ -163,7 +169,7 @@ def test_interpreter_shutdown(self):
 
             assert filenames == expected_filenames
             for i, filename in enumerate(filenames):
-                with open(os.path.join(tempdir, filename), 'rb') as f:
+                with open(os.path.join(tempdir, filename), "rb") as f:
                     assert int(f.read().strip()) == i
         finally:
             shutil.rmtree(tempdir)
@@ -187,8 +193,7 @@ def test_processes_terminate(self):
 
     def test_processes_terminate_on_executor_gc(self):
 
-        results = self.executor.map(sleep_and_return,
-                                    [0.1] * 10, range(10))
+        results = self.executor.map(sleep_and_return, [0.1] * 10, range(10))
         assert len(self.executor._processes) == self.worker_count
         processes = self.executor._processes
         executor_flags = self.executor._flags
@@ -232,8 +237,7 @@ def _wait_and_crash(cls):
 
     def test_processes_crash_handling_after_executor_gc(self):
         # Start 5 easy jobs on 5 workers
-        results = self.executor.map(sleep_and_return,
-                                    [0.01] * 5, range(5))
+        results = self.executor.map(sleep_and_return, [0.01] * 5, range(5))
 
         # Enqueue a job that will trigger a crash of one of the workers.
         # Make sure this crash does not happen before the non-failing jobs
@@ -253,7 +257,7 @@ def test_processes_crash_handling_after_executor_gc(self):
 
         if IS_PYPY:
             # Object deletion and garbage collection can be delayed under PyPy.
-            time.sleep(1.)
+            time.sleep(1.0)
             gc.collect()
 
         # Make sure that there is not other reference to the executor object.
@@ -285,8 +289,18 @@ def test_processes_crash_handling_after_executor_gc(self):
     def test_context_manager_shutdown(self):
         with self.executor_type(max_workers=5, context=self.context) as e:
             processes = e._processes
-            assert list(e.map(abs, range(-5, 5))) == \
-                [5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
+            assert list(e.map(abs, range(-5, 5))) == [
+                5,
+                4,
+                3,
+                2,
+                1,
+                0,
+                1,
+                2,
+                3,
+                4,
+            ]
 
         for p in processes.values():
             p.join()
@@ -299,7 +313,7 @@ def test_del_shutdown(self):
         del executor
         if IS_PYPY:
             # Object deletion and garbage collection can be delayed under PyPy.
-            time.sleep(1.)
+            time.sleep(1.0)
             gc.collect()
 
         executor_manager_thread.join()
@@ -325,8 +339,10 @@ def test_shutdown_no_wait(self):
 
         # submit tasks that will finish after the shutdown and make sure they
         # were started
-        res = [self.executor.submit(self._wait_and_return, x)
-               for x in range(-5, 5)]
+        res = [
+            self.executor.submit(self._wait_and_return, x)
+            for x in range(-5, 5)
+        ]
 
         self.executor.shutdown(wait=False)
 
@@ -355,8 +371,9 @@ def test_shutdown_deadlock_pickle(self):
         # a deadlock if a task fails at pickle after the shutdown call.
         # Reported in bpo-39104.
         self.executor.shutdown(wait=True)
-        with self.executor_type(max_workers=2,
-                                context=self.context) as executor:
+        with self.executor_type(
+            max_workers=2, context=self.context
+        ) as executor:
             self.executor = executor  # Allow clean up in fail_on_deadlock
 
             # Start the executor and get the executor_manager_thread to collect
@@ -395,7 +412,8 @@ def test_hang_issue39205(self):
             e.shutdown(wait=False)
         """
         stdout, stderr = check_subprocess_call(
-            [sys.executable, "-c", code], timeout=55)
+            [sys.executable, "-c", code], timeout=55
+        )
 
         _assert_no_error(stderr)
         assert stdout.strip() == "apple"
@@ -403,9 +421,11 @@ def test_hang_issue39205(self):
     @classmethod
     def _test_shutdown_and_kill_workers(cls, depth):
         executor = cls.executor_type(
-            max_workers=2, context=cls.context,
+            max_workers=2,
+            context=cls.context,
             initializer=_executor_mixin.initializer_event,
-            initargs=(_executor_mixin._test_event,))
+            initargs=(_executor_mixin._test_event,),
+        )
         assert executor.submit(sleep_and_return, 0, 42).result() == 42
 
         if depth >= 2:
@@ -435,13 +455,14 @@ def test_shutdown_and_kill_workers(self):
 
 
 class WaitTests:
-
     def test_first_completed(self):
         future1 = self.executor.submit(mul, 21, 2)
         future2 = self.executor.submit(time.sleep, 1.5)
 
-        done, not_done = futures.wait([CANCELLED_FUTURE, future1, future2],
-                                      return_when=futures.FIRST_COMPLETED)
+        done, not_done = futures.wait(
+            [CANCELLED_FUTURE, future1, future2],
+            return_when=futures.FIRST_COMPLETED,
+        )
 
         assert {future1} == done
         assert {CANCELLED_FUTURE, future2} == not_done
@@ -449,9 +470,10 @@ def test_first_completed(self):
     def test_first_completed_some_already_completed(self):
         future1 = self.executor.submit(time.sleep, 1.5)
 
-        finished, pending = futures.wait([CANCELLED_AND_NOTIFIED_FUTURE,
-                                          SUCCESSFUL_FUTURE, future1],
-                                         return_when=futures.FIRST_COMPLETED)
+        finished, pending = futures.wait(
+            [CANCELLED_AND_NOTIFIED_FUTURE, SUCCESSFUL_FUTURE, future1],
+            return_when=futures.FIRST_COMPLETED,
+        )
 
         assert {CANCELLED_AND_NOTIFIED_FUTURE, SUCCESSFUL_FUTURE} == finished
         assert {future1} == pending
@@ -459,7 +481,7 @@ def test_first_completed_some_already_completed(self):
     @classmethod
     def wait_and_raise(cls, t):
         _executor_mixin._test_event.wait(t)
-        raise Exception('this is an exception')
+        raise Exception("this is an exception")
 
     @classmethod
     def wait_and_return(cls, t):
@@ -473,10 +495,12 @@ def test_first_exception(self):
 
         def cb_done(f):
             _executor_mixin._test_event.set()
+
         future1.add_done_callback(cb_done)
 
-        finished, pending = futures.wait([future1, future2, future3],
-                                         return_when=futures.FIRST_EXCEPTION)
+        finished, pending = futures.wait(
+            [future1, future2, future3], return_when=futures.FIRST_EXCEPTION
+        )
 
         assert _executor_mixin._test_event.is_set()
 
@@ -489,22 +513,30 @@ def test_first_exception_some_already_complete(self):
         future1 = self.executor.submit(divmod, 21, 0)
         future2 = self.executor.submit(time.sleep, 1.5)
 
-        finished, pending = futures.wait([SUCCESSFUL_FUTURE, CANCELLED_FUTURE,
-                                          CANCELLED_AND_NOTIFIED_FUTURE,
-                                          future1, future2],
-                                         return_when=futures.FIRST_EXCEPTION)
-
-        assert (
-            {SUCCESSFUL_FUTURE, CANCELLED_AND_NOTIFIED_FUTURE, future1} ==
-            finished
+        finished, pending = futures.wait(
+            [
+                SUCCESSFUL_FUTURE,
+                CANCELLED_FUTURE,
+                CANCELLED_AND_NOTIFIED_FUTURE,
+                future1,
+                future2,
+            ],
+            return_when=futures.FIRST_EXCEPTION,
         )
+
+        assert {
+            SUCCESSFUL_FUTURE,
+            CANCELLED_AND_NOTIFIED_FUTURE,
+            future1,
+        } == finished
         assert {CANCELLED_FUTURE, future2} == pending
 
     def test_first_exception_one_already_failed(self):
         future1 = self.executor.submit(time.sleep, 2)
 
-        finished, pending = futures.wait([EXCEPTION_FUTURE, future1],
-                                         return_when=futures.FIRST_EXCEPTION)
+        finished, pending = futures.wait(
+            [EXCEPTION_FUTURE, future1], return_when=futures.FIRST_EXCEPTION
+        )
 
         assert {EXCEPTION_FUTURE} == finished
         assert {future1} == pending
@@ -513,13 +545,24 @@ def test_all_completed(self):
         future1 = self.executor.submit(divmod, 2, 0)
         future2 = self.executor.submit(mul, 2, 21)
 
-        finished, pending = futures.wait([SUCCESSFUL_FUTURE, EXCEPTION_FUTURE,
-                                          CANCELLED_AND_NOTIFIED_FUTURE,
-                                          future1, future2],
-                                         return_when=futures.ALL_COMPLETED)
+        finished, pending = futures.wait(
+            [
+                SUCCESSFUL_FUTURE,
+                EXCEPTION_FUTURE,
+                CANCELLED_AND_NOTIFIED_FUTURE,
+                future1,
+                future2,
+            ],
+            return_when=futures.ALL_COMPLETED,
+        )
 
-        assert {SUCCESSFUL_FUTURE, CANCELLED_AND_NOTIFIED_FUTURE,
-                EXCEPTION_FUTURE, future1, future2} == finished
+        assert {
+            SUCCESSFUL_FUTURE,
+            CANCELLED_AND_NOTIFIED_FUTURE,
+            EXCEPTION_FUTURE,
+            future1,
+            future2,
+        } == finished
         assert not pending
 
     def test_timeout(self):
@@ -532,14 +575,24 @@ def test_timeout(self):
 
         assert future1.result() == 42
 
-        finished, pending = futures.wait([CANCELLED_AND_NOTIFIED_FUTURE,
-                                          EXCEPTION_FUTURE, SUCCESSFUL_FUTURE,
-                                          future1, future2],
-                                         timeout=.1,
-                                         return_when=futures.ALL_COMPLETED)
+        finished, pending = futures.wait(
+            [
+                CANCELLED_AND_NOTIFIED_FUTURE,
+                EXCEPTION_FUTURE,
+                SUCCESSFUL_FUTURE,
+                future1,
+                future2,
+            ],
+            timeout=0.1,
+            return_when=futures.ALL_COMPLETED,
+        )
 
-        assert {CANCELLED_AND_NOTIFIED_FUTURE, EXCEPTION_FUTURE,
-                SUCCESSFUL_FUTURE, future1} == finished
+        assert {
+            CANCELLED_AND_NOTIFIED_FUTURE,
+            EXCEPTION_FUTURE,
+            SUCCESSFUL_FUTURE,
+            future1,
+        } == finished
         assert {future2} == pending
 
         _executor_mixin._test_event.set()
@@ -553,32 +606,50 @@ def test_no_timeout(self):
         future1 = self.executor.submit(mul, 2, 21)
         future2 = self.executor.submit(mul, 7, 6)
 
-        completed = set(futures.as_completed([CANCELLED_AND_NOTIFIED_FUTURE,
-                                              EXCEPTION_FUTURE,
-                                              SUCCESSFUL_FUTURE,
-                                              future1, future2]))
-        assert {CANCELLED_AND_NOTIFIED_FUTURE, EXCEPTION_FUTURE,
-                SUCCESSFUL_FUTURE, future1, future2} == completed
+        completed = set(
+            futures.as_completed(
+                [
+                    CANCELLED_AND_NOTIFIED_FUTURE,
+                    EXCEPTION_FUTURE,
+                    SUCCESSFUL_FUTURE,
+                    future1,
+                    future2,
+                ]
+            )
+        )
+        assert {
+            CANCELLED_AND_NOTIFIED_FUTURE,
+            EXCEPTION_FUTURE,
+            SUCCESSFUL_FUTURE,
+            future1,
+            future2,
+        } == completed
 
     def test_zero_timeout(self):
         future1 = self.executor.submit(time.sleep, 2)
         completed_futures = set()
         with pytest.raises(futures.TimeoutError):
             for future in futures.as_completed(
-                    [CANCELLED_AND_NOTIFIED_FUTURE,
-                     EXCEPTION_FUTURE,
-                     SUCCESSFUL_FUTURE,
-                     future1],
-                    timeout=0):
+                [
+                    CANCELLED_AND_NOTIFIED_FUTURE,
+                    EXCEPTION_FUTURE,
+                    SUCCESSFUL_FUTURE,
+                    future1,
+                ],
+                timeout=0,
+            ):
                 completed_futures.add(future)
 
-        assert {CANCELLED_AND_NOTIFIED_FUTURE, EXCEPTION_FUTURE,
-                SUCCESSFUL_FUTURE} == completed_futures
+        assert {
+            CANCELLED_AND_NOTIFIED_FUTURE,
+            EXCEPTION_FUTURE,
+            SUCCESSFUL_FUTURE,
+        } == completed_futures
 
     def test_duplicate_futures(self):
         # Issue 20367. Duplicate futures should not raise exceptions or give
         # duplicate responses.
-        future1 = self.executor.submit(time.sleep, .1)
+        future1 = self.executor.submit(time.sleep, 0.1)
         completed = list(futures.as_completed([future1, future1]))
         assert len(completed) == 1
 
@@ -595,13 +666,14 @@ def test_submit_keyword(self):
         assert 16 == future.result()
 
     def test_map(self):
-        assert list(self.executor.map(pow, range(10), range(10))) == \
-            list(map(pow, range(10), range(10)))
+        assert list(self.executor.map(pow, range(10), range(10))) == list(
+            map(pow, range(10), range(10))
+        )
 
     def test_map_exception(self):
         i = self.executor.map(divmod, [1, 1, 1, 1], [2, 3, 0, 5])
-        assert next(i), (0 == 1)
-        assert next(i), (0 == 1)
+        assert next(i), 0 == 1
+        assert next(i), 0 == 1
         with pytest.raises(ZeroDivisionError):
             next(i)
 
@@ -621,9 +693,10 @@ def test_shutdown_race_issue12456(self):
         self.executor.shutdown()
 
     @pytest.mark.skipif(
-            platform.python_implementation() != "CPython" or
-            (sys.version_info >= (3, 8, 0) and sys.version_info < (3, 8, 2)),
-            reason="Underlying bug fixed upstream starting Python 3.8.2")
+        platform.python_implementation() != "CPython"
+        or (sys.version_info >= (3, 8, 0) and sys.version_info < (3, 8, 2)),
+        reason="Underlying bug fixed upstream starting Python 3.8.2",
+    )
     def test_no_stale_references(self):
         # Issue #16284: check that the executors don't unnecessarily hang onto
         # references.
@@ -675,12 +748,18 @@ def bad_map():
             list(self.executor.map(pow, range(40), range(40), chunksize=-1))
 
         ref = list(map(pow, range(40), range(40)))
-        assert list(self.executor.map(pow, range(40), range(40), chunksize=6)
-                    ) == ref
-        assert list(self.executor.map(pow, range(40), range(40), chunksize=50)
-                    ) == ref
-        assert list(self.executor.map(pow, range(40), range(40), chunksize=40)
-                    ) == ref
+        assert (
+            list(self.executor.map(pow, range(40), range(40), chunksize=6))
+            == ref
+        )
+        assert (
+            list(self.executor.map(pow, range(40), range(40), chunksize=50))
+            == ref
+        )
+        assert (
+            list(self.executor.map(pow, range(40), range(40), chunksize=40))
+            == ref
+        )
         with pytest.raises(ValueError):
             bad_map()
 
@@ -701,14 +780,14 @@ def test_traceback(self):
 
         cause = exc.__cause__
         assert type(cause) is process_executor._RemoteTraceback
-        assert 'raise RuntimeError(123)  # some comment' in cause.tb
+        assert "raise RuntimeError(123)  # some comment" in cause.tb
 
     #
     # The following tests are new additions to the test suite originally
     # backported from the Python 3 concurrent.futures package.
     #
 
-    def _test_thread_safety(self, thread_idx, results, timeout=30.):
+    def _test_thread_safety(self, thread_idx, results, timeout=30.0):
         try:
             # submit a mix of very simple tasks with map and submit,
             # cancel some of them and check the results
@@ -717,8 +796,9 @@ def _test_thread_safety(self, thread_idx, results, timeout=30.):
                 # Make it more likely for scheduling threads to overtake one
                 # another
                 time.sleep(0.001)
-            submit_futures = [self.executor.submit(time.sleep, 0.0001)
-                              for _ in range(20)]
+            submit_futures = [
+                self.executor.submit(time.sleep, 0.0001) for _ in range(20)
+            ]
             for i, f in enumerate(submit_futures):
                 if i % 2 == 0:
                     f.cancel()
@@ -729,7 +809,7 @@ def _test_thread_safety(self, thread_idx, results, timeout=30.):
             for i, f in enumerate(submit_futures):
                 if i % 2 == 1 or not f.cancelled():
                     assert f.result(timeout=timeout) is None
-            results[thread_idx] = 'ok'
+            results[thread_idx] = "ok"
         except Exception as e:
             # Ensure that py.test can report the content of the exception
             # by raising it in the main test thread
@@ -739,8 +819,10 @@ def test_thread_safety(self):
         # Check that our process-pool executor can be shared to schedule work
         # by concurrent threads
         results = [None] * 10
-        threads = [Thread(target=self._test_thread_safety, args=(i, results))
-                   for i in range(len(results))]
+        threads = [
+            Thread(target=self._test_thread_safety, args=(i, results))
+            for i in range(len(results))
+        ]
 
         for t in threads:
             t.start()
@@ -767,22 +849,24 @@ def _collect_and_submit_next(future):
                 future.add_done_callback(_collect_and_submit_next)
 
         # Start 3 concurrent callbacks chains
-        fa = executor.submit(self.return_inputs, 'chain a', 100)
+        fa = executor.submit(self.return_inputs, "chain a", 100)
         fa.add_done_callback(_collect_and_submit_next)
-        fb = executor.submit(self.return_inputs, 'chain b', 50)
+        fb = executor.submit(self.return_inputs, "chain b", 50)
         fb.add_done_callback(_collect_and_submit_next)
-        fc = executor.submit(self.return_inputs, 'chain c', 60)
+        fc = executor.submit(self.return_inputs, "chain c", 60)
         fc.add_done_callback(_collect_and_submit_next)
-        assert fa.result() == ('chain a', 100)
-        assert fb.result() == ('chain b', 50)
-        assert fc.result() == ('chain c', 60)
+        assert fa.result() == ("chain a", 100)
+        assert fb.result() == ("chain b", 50)
+        assert fc.result() == ("chain c", 60)
 
         # Wait a maximum of 5s for the asynchronous callback chains to complete
         patience = 500
         while True:
-            if (collected['chain a'] == list(range(100, -1, -1)) and
-                    collected['chain b'] == list(range(50, -1, -1)) and
-                    collected['chain c'] == list(range(60, -1, -1))):
+            if (
+                collected["chain a"] == list(range(100, -1, -1))
+                and collected["chain b"] == list(range(50, -1, -1))
+                and collected["chain c"] == list(range(60, -1, -1))
+            ):
                 # the recursive callback chains have completed successfully
                 break
             elif patience < 0:
@@ -797,10 +881,11 @@ def _collect_and_submit_next(future):
     def test_worker_timeout(self):
         self.executor.shutdown(wait=True)
         self.check_no_running_workers(patience=5)
-        timeout = getattr(self, 'min_worker_timeout', .01)
+        timeout = getattr(self, "min_worker_timeout", 0.01)
         try:
             self.executor = self.executor_type(
-                max_workers=4, context=self.context, timeout=timeout)
+                max_workers=4, context=self.context, timeout=timeout
+            )
         except NotImplementedError as e:
             self.skipTest(str(e))
 
@@ -809,7 +894,7 @@ def test_worker_timeout(self):
                 # It's ok to get a warning about the worker interrupted by the
                 # short timeout while tasks are pending in the queue on
                 # overloaded CI hosts.
-                warnings.simplefilter('ignore', category=UserWarning)
+                warnings.simplefilter("ignore", category=UserWarning)
 
                 # Trigger worker spawn for lazy executor implementations
                 for _ in self.executor.map(id, range(8)):
@@ -824,11 +909,11 @@ def test_worker_timeout(self):
 
     @classmethod
     def reducer_in(cls, obj):
-        return MyObject, (obj.value + 5, )
+        return MyObject, (obj.value + 5,)
 
     @classmethod
     def reducer_out(cls, obj):
-        return MyObject, (7 * obj.value, )
+        return MyObject, (7 * obj.value,)
 
     def test_serialization(self):
         """Test custom serialization for process_executor"""
@@ -843,15 +928,18 @@ def test_serialization(self):
         # Create a new executor to ensure that we did not mess with the
         # existing module level serialization
         executor = self.executor_type(
-            max_workers=2, context=self.context, job_reducers=job_reducers,
-            result_reducers=result_reducers
+            max_workers=2,
+            context=self.context,
+            job_reducers=job_reducers,
+            result_reducers=result_reducers,
         )
         self.executor = self.executor_type(max_workers=2, context=self.context)
 
         obj = MyObject(1)
         try:
-            ret_obj_custom = executor.submit(
-                    self.return_inputs, obj).result()[0]
+            ret_obj_custom = executor.submit(self.return_inputs, obj).result()[
+                0
+            ]
             ret_obj = self.executor.submit(self.return_inputs, obj).result()[0]
 
             assert ret_obj.value == 1
@@ -870,45 +958,57 @@ def _test_max_depth(cls, max_depth=10, kill_workers=False, ctx=None):
         finally:
             executor.shutdown(wait=True, kill_workers=kill_workers)
 
-    @pytest.mark.parametrize('kill_workers', [True, False])
+    @pytest.mark.parametrize("kill_workers", [True, False])
     def test_max_depth(self, kill_workers):
         from loky.process_executor import MAX_DEPTH
-        if self.context.get_start_method() == 'fork':
+
+        if self.context.get_start_method() == "fork":
             # For 'fork', we do not allow nested process as the threads ends
             # up in messy states
             with pytest.raises(LokyRecursionError):
                 self._test_max_depth(max_depth=2, ctx=self.context)
             return
 
-        assert self._test_max_depth(max_depth=MAX_DEPTH,
-                                    kill_workers=kill_workers,
-                                    ctx=self.context) == 42
+        assert (
+            self._test_max_depth(
+                max_depth=MAX_DEPTH,
+                kill_workers=kill_workers,
+                ctx=self.context,
+            )
+            == 42
+        )
 
         with pytest.raises(LokyRecursionError):
-            self._test_max_depth(max_depth=MAX_DEPTH + 1,
-                                 kill_workers=kill_workers,
-                                 ctx=self.context)
+            self._test_max_depth(
+                max_depth=MAX_DEPTH + 1,
+                kill_workers=kill_workers,
+                ctx=self.context,
+            )
 
     @pytest.mark.high_memory
-    @pytest.mark.skipif(sys.maxsize < 2 ** 32,
-                        reason="Test requires a 64 bit version of Python")
+    @pytest.mark.skipif(
+        sys.maxsize < 2**32,
+        reason="Test requires a 64 bit version of Python",
+    )
     @pytest.mark.skipif(
         sys.version_info < (3, 8),
-        reason="Python version does not support pickling objects of size > 2 ** 31GB"
+        reason="Python version does not support pickling objects of size > 2 ** 31GB",
     )
     def test_no_failure_on_large_data_send(self):
-        data = b'\x00' * int(2.2e9)
+        data = b"\x00" * int(2.2e9)
         self.executor.submit(id, data).result()
 
     @pytest.mark.high_memory
-    @pytest.mark.skipif(sys.maxsize < 2 ** 32,
-                        reason="Test requires a 64 bit version of Python")
+    @pytest.mark.skipif(
+        sys.maxsize < 2**32,
+        reason="Test requires a 64 bit version of Python",
+    )
     @pytest.mark.skipif(
         sys.version_info >= (3, 8),
-        reason="Python version supports pickling objects of size > 2 ** 31GB"
+        reason="Python version supports pickling objects of size > 2 ** 31GB",
     )
     def test_expected_failure_on_large_data_send(self):
-        data = b'\x00' * int(2.2e9)
+        data = b"\x00" * int(2.2e9)
         with pytest.raises(RuntimeError):
             self.executor.submit(id, data).result()
 
@@ -919,10 +1019,11 @@ def test_memory_leak_protection(self):
         executor = self.executor_type(1, context=self.context)
 
         def _leak_some_memory(size=int(3e6), delay=0.001):
-            """function that leaks some memory """
+            """function that leaks some memory"""
             from loky import process_executor
+
             process_executor._MEMORY_LEAK_CHECK_DELAY = 0.1
-            if getattr(os, '_loky_leak', None) is None:
+            if getattr(os, "_loky_leak", None) is None:
                 os._loky_leak = []
 
             os._loky_leak.append(b"\x00" * size)
@@ -935,7 +1036,7 @@ def _leak_some_memory(size=int(3e6), delay=0.001):
             leaked_size = sum(len(buffer) for buffer in os._loky_leak)
             return os.getpid(), leaked_size
 
-        with pytest.warns(UserWarning, match='memory leak'):
+        with pytest.warns(UserWarning, match="memory leak"):
             # Total run time should be 3s which is way over the 1s cooldown
             # period between two consecutive memory checks in the worker.
             futures = [executor.submit(_leak_some_memory) for _ in range(300)]
@@ -963,6 +1064,7 @@ def test_reference_cycle_collection(self):
         def _create_cyclic_reference(delay=0.001):
             """function that creates a cyclic reference"""
             from loky import process_executor
+
             process_executor._USE_PSUTIL = False
             process_executor._MEMORY_LEAK_CHECK_DELAY = 0.1
 
@@ -970,7 +1072,8 @@ class A:
                 def __init__(self, size=int(1e6)):
                     self.data = b"\x00" * size
                     self.a = self
-            if getattr(os, '_loky_cyclic_weakrefs', None) is None:
+
+            if getattr(os, "_loky_cyclic_weakrefs", None) is None:
                 os._loky_cyclic_weakrefs = []
 
             a = A()
@@ -1010,7 +1113,7 @@ def _test_child_env(var_name):
     def test_child_env_executor(self):
         # Test that for loky context, setting argument env correctly overwrite
         # the environment of the child process.
-        if self.context.get_start_method() != 'loky':
+        if self.context.get_start_method() != "loky":
             pytest.skip("Only work with loky context")
 
         var_name = "loky_child_env_executor"
@@ -1075,9 +1178,7 @@ def check_viztracer_active_and_custom_init():
         try:
             tracer.start()
             with self.executor_type(
-                1,
-                context=self.context,
-                initializer=_custom_initializer
+                1, context=self.context, initializer=_custom_initializer
             ) as e:
                 assert e.submit(
                     check_viztracer_active_and_custom_init
@@ -1087,7 +1188,7 @@ def check_viztracer_active_and_custom_init():
 
     def test_exception_cause_with_tblib(self):
         "Ensure tampering with exception pickling do not break __cause__ propagation"
-        tblib_pickling_support = pytest.importorskip('tblib.pickling_support')
+        tblib_pickling_support = pytest.importorskip("tblib.pickling_support")
 
         error_message = "This is the error message"
 
@@ -1113,4 +1214,3 @@ def _custom_initializer():
     use cloudpickle to pickle the initializer.
     """
     loky._custom_global_var = 42
-
diff --git a/tests/conftest.py b/tests/conftest.py
index ef21d7e2..86a03e52 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -5,10 +5,17 @@
 
 
 def pytest_addoption(parser):
-    parser.addoption("--loky-verbosity", type=int, default=logging.DEBUG,
-                     help="log-level: integer, SUBDEBUG(5) - INFO(20)")
-    parser.addoption("--skip-high-memory", action="store_true",
-                     help="skip high-memory test to avoid conflict on CI.")
+    parser.addoption(
+        "--loky-verbosity",
+        type=int,
+        default=logging.DEBUG,
+        help="log-level: integer, SUBDEBUG(5) - INFO(20)",
+    )
+    parser.addoption(
+        "--skip-high-memory",
+        action="store_true",
+        help="skip high-memory test to avoid conflict on CI.",
+    )
 
 
 def log_lvl(request):
@@ -20,10 +27,13 @@ def pytest_configure(config):
     """Setup multiprocessing logging for loky testing"""
     logging._levelToName[5] = "SUBDEBUG"
     log = log_to_stderr(config.getoption("--loky-verbosity"))
-    log.handlers[0].setFormatter(logging.Formatter(
-        '[%(levelname)s:%(processName)s:%(threadName)s] %(message)s'))
+    log.handlers[0].setFormatter(
+        logging.Formatter(
+            "[%(levelname)s:%(processName)s:%(threadName)s] %(message)s"
+        )
+    )
 
-    warnings.simplefilter('always')
+    warnings.simplefilter("always")
 
     config.addinivalue_line("markers", "timeout")
     config.addinivalue_line("markers", "broken_pool")
@@ -35,7 +45,8 @@ def pytest_collection_modifyitems(config, items):
         # --skip-high-memory given in cli: skip high-memory tests
         return
     skip_high_memory = pytest.mark.skip(
-        reason="--skip-high-memory option was provided")
+        reason="--skip-high-memory option was provided"
+    )
     for item in items:
         if "high_memory" in item.keywords:
             item.add_marker(skip_high_memory)
diff --git a/tests/test_cloudpickle_wrapper.py b/tests/test_cloudpickle_wrapper.py
index 5dfd0390..e1bfc8ae 100644
--- a/tests/test_cloudpickle_wrapper.py
+++ b/tests/test_cloudpickle_wrapper.py
@@ -12,7 +12,6 @@
 
 
 class TestCloudpickleWrapper:
-
     def test_isolated_pickler_dispatch_tables(self):
         class A:
             pass
@@ -21,11 +20,9 @@ class B:
             pass
 
         iob1 = io.BytesIO()
-        p1 = get_loky_pickler()(iob1,
-                                reducers={A: lambda obj: (int, (42,))})
+        p1 = get_loky_pickler()(iob1, reducers={A: lambda obj: (int, (42,))})
         iob2 = io.BytesIO()
-        p2 = get_loky_pickler()(iob2,
-                                reducers={B: lambda obj: (int, (42,))})
+        p2 = get_loky_pickler()(iob2, reducers={B: lambda obj: (int, (42,))})
 
         assert p1.dispatch_table is not p2.dispatch_table
 
@@ -64,16 +61,16 @@ def test_func(x):
         try:
             fid, filename = mkstemp(suffix="_joblib.py")
             os.close(fid)
-            with open(filename, mode='w') as f:
+            with open(filename, mode="w") as f:
                 f.write(code)
             cmd += [filename]
-            check_subprocess_call(cmd, stdout_regex='ok', timeout=10)
+            check_subprocess_call(cmd, stdout_regex="ok", timeout=10)
 
             # Makes sure that if LOKY_PICKLER is set to default pickle, the
             # tasks are not wrapped with cloudpickle and it is not possible
             # using functions from the main module.
-            env = {'LOKY_PICKLER': 'pickle'}
-            with pytest.raises(ValueError, match='A task has failed to un-s'):
+            env = {"LOKY_PICKLER": "pickle"}
+            with pytest.raises(ValueError, match="A task has failed to un-s"):
                 check_subprocess_call(cmd, timeout=10, env=env)
         finally:
             os.unlink(filename)
@@ -107,10 +104,10 @@ def pass_all(*args, **kwargs):
         try:
             fid, filename = mkstemp(suffix="_joblib.py")
             os.close(fid)
-            with open(filename, mode='w') as f:
+            with open(filename, mode="w") as f:
                 f.write(code)
             cmd += [filename]
-            check_subprocess_call(cmd, stdout_regex='ok', timeout=10)
+            check_subprocess_call(cmd, stdout_regex="ok", timeout=10)
         finally:
             os.unlink(filename)
 
@@ -162,17 +159,18 @@ def return_func(self):
         try:
             fid, filename = mkstemp(suffix="_joblib.py")
             os.close(fid)
-            with open(filename, mode='w') as f:
+            with open(filename, mode="w") as f:
                 f.write(code)
             cmd += [filename]
 
-            env = {'LOKY_PICKLER': 'pickle'}
-            check_subprocess_call(cmd, stdout_regex='ok', timeout=10, env=env)
+            env = {"LOKY_PICKLER": "pickle"}
+            check_subprocess_call(cmd, stdout_regex="ok", timeout=10, env=env)
         finally:
             os.unlink(filename)
 
-    @pytest.mark.parametrize('loky_pickler',
-                             [None, "''", "'cloudpickle'", "'pickle'"])
+    @pytest.mark.parametrize(
+        "loky_pickler", [None, "''", "'cloudpickle'", "'pickle'"]
+    )
     def test_set_loky_pickler(self, loky_pickler):
         # Test that the function set_loky_pickler correctly changes the pickler
         # used in loky.
@@ -244,7 +242,7 @@ def test_func(x):
         try:
             fid, filename = mkstemp(suffix="_joblib.py")
             os.close(fid)
-            with open(filename, mode='w') as f:
+            with open(filename, mode="w") as f:
                 f.write(code)
             cmd += [filename]
             if loky_pickler == "'pickle'":
@@ -252,7 +250,7 @@ def test_func(x):
                 with pytest.raises(ValueError, match=match):
                     check_subprocess_call(cmd, timeout=10)
             else:
-                check_subprocess_call(cmd, stdout_regex='ok', timeout=10)
+                check_subprocess_call(cmd, stdout_regex="ok", timeout=10)
         finally:
             os.unlink(filename)
 
diff --git a/tests/test_futures.py b/tests/test_futures.py
index e827d250..24fe9de0 100644
--- a/tests/test_futures.py
+++ b/tests/test_futures.py
@@ -2,8 +2,13 @@
 import pytest
 import threading
 from concurrent import futures
-from concurrent.futures._base import (PENDING, RUNNING, CANCELLED,
-                                      CANCELLED_AND_NOTIFIED, FINISHED)
+from concurrent.futures._base import (
+    PENDING,
+    RUNNING,
+    CANCELLED,
+    CANCELLED_AND_NOTIFIED,
+    FINISHED,
+)
 
 from loky._base import Future
 
@@ -46,8 +51,8 @@ def fn(callback_future):
 
         f = Future()
         f.add_done_callback(fn)
-        f.set_exception(Exception('test'))
-        assert ('test',) == callback_exception[0].args
+        f.set_exception(Exception("test"))
+        assert ("test",) == callback_exception[0].args
 
     def test_done_callback_with_cancel(self):
         was_cancelled = [None]
@@ -63,6 +68,7 @@ def fn(callback_future):
     def test_done_callback_raises(self):
         with captured_stderr() as stderr:
             import logging
+
             log = logging.getLogger("concurrent.futures")
             log.addHandler(logging.StreamHandler())
             raising_was_called = [False]
@@ -70,7 +76,7 @@ def test_done_callback_raises(self):
 
             def raising_fn(callback_future):
                 raising_was_called[0] = True
-                raise Exception('foobar')
+                raise Exception("foobar")
 
             def fn(callback_future):
                 fn_was_called[0] = True
@@ -81,7 +87,7 @@ def fn(callback_future):
             f.set_result(5)
             assert raising_was_called[0]
             assert fn_was_called[0]
-            assert 'Exception: foobar' in stderr.getvalue()
+            assert "Exception: foobar" in stderr.getvalue()
 
             del log.handlers[:]
 
@@ -103,9 +109,9 @@ def fn(callback_future):
             callback_exception[0] = callback_future.exception()
 
         f = Future()
-        f.set_exception(Exception('test'))
+        f.set_exception(Exception("test"))
         f.add_done_callback(fn)
-        assert ('test',) == callback_exception[0].args
+        assert ("test",) == callback_exception[0].args
 
     def test_done_callback_already_cancelled(self):
         was_cancelled = [None]
@@ -120,18 +126,47 @@ def fn(callback_future):
 
     def test_repr(self):
         import re
-        assert re.match('<Future at 0x[0-9a-f]+ state=pending>',
-                        repr(PENDING_FUTURE)).pos > -1
-        assert re.match('<Future at 0x[0-9a-f]+ state=running>',
-                        repr(RUNNING_FUTURE)).pos > -1
-        assert re.match('<Future at 0x[0-9a-f]+ state=cancelled>',
-                        repr(CANCELLED_FUTURE)).pos > -1
-        assert re.match('<Future at 0x[0-9a-f]+ state=cancelled>',
-                        repr(CANCELLED_AND_NOTIFIED_FUTURE)).pos > -1
-        assert re.match('<Future at 0x[0-9a-f]+ state=finished raised '
-                        'OSError>', repr(EXCEPTION_FUTURE)).pos > -1
-        assert re.match('<Future at 0x[0-9a-f]+ state=finished returned int>',
-                        repr(SUCCESSFUL_FUTURE)).pos > -1
+
+        assert (
+            re.match(
+                "<Future at 0x[0-9a-f]+ state=pending>", repr(PENDING_FUTURE)
+            ).pos
+            > -1
+        )
+        assert (
+            re.match(
+                "<Future at 0x[0-9a-f]+ state=running>", repr(RUNNING_FUTURE)
+            ).pos
+            > -1
+        )
+        assert (
+            re.match(
+                "<Future at 0x[0-9a-f]+ state=cancelled>",
+                repr(CANCELLED_FUTURE),
+            ).pos
+            > -1
+        )
+        assert (
+            re.match(
+                "<Future at 0x[0-9a-f]+ state=cancelled>",
+                repr(CANCELLED_AND_NOTIFIED_FUTURE),
+            ).pos
+            > -1
+        )
+        assert (
+            re.match(
+                "<Future at 0x[0-9a-f]+ state=finished raised " "OSError>",
+                repr(EXCEPTION_FUTURE),
+            ).pos
+            > -1
+        )
+        assert (
+            re.match(
+                "<Future at 0x[0-9a-f]+ state=finished returned int>",
+                repr(SUCCESSFUL_FUTURE),
+            ).pos
+            > -1
+        )
 
     def test_cancel(self):
         f1 = create_future(state=PENDING)
@@ -200,7 +235,7 @@ def test_result_with_success(self):
         def notification(ready):
             # Wait until the main thread is waiting for the result.
             ready.wait(1)
-            time.sleep(.1)
+            time.sleep(0.1)
             f1.set_result(42)
 
         ready = threading.Event()
@@ -215,7 +250,7 @@ def test_result_with_cancel(self):
         def notification(ready):
             # Wait until the main thread is waiting for the result.
             ready.wait(1)
-            time.sleep(.1)
+            time.sleep(0.1)
             f1.cancel()
 
         ready = threading.Event()
@@ -243,7 +278,7 @@ def test_exception_with_success(self):
         def notification(ready):
             # Wait until the main thread is waiting for the exception.
             ready.wait(1)
-            time.sleep(.1)
+            time.sleep(0.1)
             with f1._condition:
                 f1._state = FINISHED
                 f1._exception = OSError()
diff --git a/tests/test_loky_backend.py b/tests/test_loky_backend.py
index 5836b827..7f5b626a 100644
--- a/tests/test_loky_backend.py
+++ b/tests/test_loky_backend.py
@@ -13,8 +13,12 @@
 from loky.backend.context import START_METHODS
 from loky.backend.utils import kill_process_tree
 
-from .utils import (TimingWrapper, check_subprocess_call, with_parallel_sum,
-                    _run_openmp_parallel_sum)
+from .utils import (
+    TimingWrapper,
+    check_subprocess_call,
+    with_parallel_sum,
+    _run_openmp_parallel_sum,
+)
 
 if not hasattr(socket, "socketpair"):
 
@@ -32,10 +36,11 @@ def socketpair():
 
 DELTA = 0.1
 ctx_loky = get_context("loky")
-HAVE_SEND_HANDLE = (sys.platform == "win32" or
-                    (hasattr(socket, 'CMSG_LEN') and
-                     hasattr(socket, 'SCM_RIGHTS') and
-                     hasattr(socket.socket, 'sendmsg')))
+HAVE_SEND_HANDLE = sys.platform == "win32" or (
+    hasattr(socket, "CMSG_LEN")
+    and hasattr(socket, "SCM_RIGHTS")
+    and hasattr(socket.socket, "sendmsg")
+)
 HAVE_FROM_FD = hasattr(socket, "fromfd")
 
 
@@ -61,8 +66,7 @@ class TestLokyBackend:
 
     @classmethod
     def teardown_class(cls):
-        """Clean up the test environment from any remaining subprocesses.
-        """
+        """Clean up the test environment from any remaining subprocesses."""
         for child_process in cls.active_children():
             kill_process_tree(child_process)
 
@@ -101,13 +105,12 @@ def _test_process(cls, q, sq, *args, **kwds):
 
     @pytest.mark.parametrize("context_name", ["loky", "loky_init_main"])
     def test_process(self, context_name):
-        """behavior of Process variables and functional connection objects
-        """
+        """behavior of Process variables and functional connection objects"""
         q = self.Queue()
         sq = self.SimpleQueue()
         args = (q, sq, 1, 2)
-        kwargs = {'hello': 23, 'bye': 2.54}
-        name = 'TestLokyProcess'
+        kwargs = {"hello": 23, "bye": 2.54}
+        name = "TestLokyProcess"
         ctx = get_context(context_name)
         p = ctx.Process(
             target=self._test_process, args=args, kwargs=kwargs, name=name
@@ -172,7 +175,7 @@ def test_socket(self):
 
         client.settimeout(5)
 
-        msg = b'42'
+        msg = b"42"
         client.send(msg)
         assert client.recv(2) == msg
 
@@ -182,9 +185,11 @@ def test_socket(self):
         client.close()
         server.close()
 
-    @pytest.mark.skipif(not HAVE_SEND_HANDLE or not HAVE_FROM_FD,
-                        reason="This system cannot send handle between process"
-                        ". Connections object should be shared at spawning.")
+    @pytest.mark.skipif(
+        not HAVE_SEND_HANDLE or not HAVE_FROM_FD,
+        reason="This system cannot send handle between process"
+        ". Connections object should be shared at spawning.",
+    )
     def test_socket_queue(self):
         """sockets can be pickled in a queue and are able to send/recv"""
         q = self.SimpleQueue()
@@ -195,7 +200,7 @@ def test_socket_queue(self):
         server, client = socket.socketpair()
         q.put(server)
 
-        msg = b'42'
+        msg = b"42"
         client.settimeout(5)
         client.send(msg)
         assert client.recv(2) == msg
@@ -210,11 +215,12 @@ def test_connection(self):
         """connections can be pickled at spawn and are able to send/recv"""
         parent_connection, child_connection = self.Pipe(duplex=True)
 
-        p = self.Process(target=self._test_connection,
-                         args=(child_connection,))
+        p = self.Process(
+            target=self._test_connection, args=(child_connection,)
+        )
         p.start()
 
-        msg = b'42'
+        msg = b"42"
         parent_connection.send(msg)
         assert parent_connection.recv() == msg
 
@@ -223,9 +229,11 @@ def test_connection(self):
         parent_connection.close()
         child_connection.close()
 
-    @pytest.mark.skipif(not HAVE_SEND_HANDLE,
-                        reason="This system cannot send handle between. "
-                        "Connections object should be shared at spawning.")
+    @pytest.mark.skipif(
+        not HAVE_SEND_HANDLE,
+        reason="This system cannot send handle between. "
+        "Connections object should be shared at spawning.",
+    )
     def test_connection_queue(self):
         """connections can be pickled in a queue and are able to send/recv"""
         q = self.SimpleQueue()
@@ -235,7 +243,7 @@ def test_connection_queue(self):
         parent_connection, child_connection = self.Pipe(duplex=True)
         q.put(child_connection)
 
-        msg = b'42'
+        msg = b"42"
         parent_connection.send(msg)
         assert parent_connection.recv() == msg
 
@@ -246,18 +254,19 @@ def test_connection_queue(self):
 
     @staticmethod
     def _test_child_env(key, queue):
-        queue.put(os.environ.get(key, 'not set'))
+        queue.put(os.environ.get(key, "not set"))
 
     def test_child_env_process(self):
-        key = 'loky_child_env_process'
-        value = 'loky works'
+        key = "loky_child_env_process"
+        value = "loky works"
         out_queue = self.SimpleQueue()
         try:
             # Test that the environment variable is correctly copied in the
             # child process.
             os.environ[key] = value
-            p = self.Process(target=self._test_child_env,
-                             args=(key, out_queue))
+            p = self.Process(
+                target=self._test_child_env, args=(key, out_queue)
+            )
             p.start()
             child_var = out_queue.get()
             p.join()
@@ -266,9 +275,12 @@ def test_child_env_process(self):
 
             # Test that the environment variable is correctly overwritted by
             # using the `env` argument in Process.
-            new_value = 'loky rocks'
-            p = self.Process(target=self._test_child_env,
-                             args=(key, out_queue), env={key: new_value})
+            new_value = "loky rocks"
+            p = self.Process(
+                target=self._test_child_env,
+                args=(key, out_queue),
+                env={key: new_value},
+            )
             p.start()
             child_var = out_queue.get()
             p.join()
@@ -312,11 +324,12 @@ def test_terminate(self):
         p.terminate()
 
         MAX_JOIN_TIME = 10
-        if hasattr(signal, 'alarm'):
+        if hasattr(signal, "alarm"):
             # On the Gentoo buildbot waitpid() often seems to block forever.
             # We use alarm() to interrupt it if it blocks for too long.
             def handler(*args):
-                raise RuntimeError(f'join took too long: {p}')
+                raise RuntimeError(f"join took too long: {p}")
+
             old_handler = signal.signal(signal.SIGALRM, handler)
             try:
                 signal.alarm(MAX_JOIN_TIME)
@@ -374,15 +387,7 @@ def test_recursion(self):
             a = rconn.recv()
             result.append(a)
 
-        expected = [
-            [],
-            [0],
-            [0, 0],
-            [0, 1],
-            [1],
-            [1, 0],
-            [1, 1]
-        ]
+        expected = [[], [0], [0, 0], [0, 1], [1], [1, 0], [1, 1]]
         assert result == expected
 
     @classmethod
@@ -404,7 +409,8 @@ def test_sentinel(self):
     @classmethod
     def _test_wait_sentinel(cls):
         from signal import SIGTERM
-        time.sleep(.1)
+
+        time.sleep(0.1)
         os.kill(os.getpid(), SIGTERM)
 
     def test_wait_sentinel(self):
@@ -415,7 +421,7 @@ def test_wait_sentinel(self):
         assert isinstance(p.sentinel, int)
         assert not wait([p.sentinel], timeout=0.0)
         assert wait([p.sentinel], timeout=5), p.exitcode
-        expected_code = 15 if sys.platform == 'win32' else -15
+        expected_code = 15 if sys.platform == "win32" else -15
         p.join()  # force refresh of p.exitcode
         assert p.exitcode == expected_code
 
@@ -439,8 +445,14 @@ def _test_sync_object_handling(cls, started, stop, conn, w):
         w: int
             fileno of the writable end of the Pipe, it should be closed
         """
-        to_clean_up = [cls.Semaphore(0), cls.BoundedSemaphore(1),  # noqa: F841
-                       cls.Lock(), cls.RLock(), cls.Condition(), cls.Event()]
+        to_clean_up = [
+            cls.Semaphore(0),
+            cls.BoundedSemaphore(1),  # noqa: F841
+            cls.Lock(),
+            cls.RLock(),
+            cls.Condition(),
+            cls.Event(),
+        ]
         started.set()
         assert conn.recv_bytes() == b"foo"
         with pytest.raises(OSError):
@@ -453,13 +465,17 @@ def _check_fds(self, pid, w):
         Return a list of open named semaphores
         """
         import subprocess
+
         try:
             out = subprocess.check_output(
-                f"lsof -a -Fftn -p {pid} -d ^txt,^cwd,^rtd".split(), text=True)
+                f"lsof -a -Fftn -p {pid} -d ^txt,^cwd,^rtd".split(), text=True
+            )
             lines = out.splitlines()[1:]
         except (FileNotFoundError, OSError):
-            print("lsof does not exist on this platform. Skip open files"
-                  "check.")
+            print(
+                "lsof does not exist on this platform. Skip open files"
+                "check."
+            )
             return []
 
         n_pipe = 0
@@ -468,26 +484,26 @@ def _check_fds(self, pid, w):
 
             # Check if fd is a standard IO file. For python 3.x stdin
             # should be closed.
-            is_std = (fd in ["f1", "f2"])
+            is_std = fd in ["f1", "f2"]
 
             # Check if fd is a pipe
-            is_pipe = (t in ["tPIPE", "tFIFO"])
+            is_pipe = t in ["tPIPE", "tFIFO"]
             n_pipe += is_pipe
 
             # Check if fd is open for the rng. This can happen on different
             # plateform and depending of the python version.
-            is_rng = (name == "n/dev/urandom")
+            is_rng = name == "n/dev/urandom"
 
             # Check if fd is a semaphore or an open library. Store all the
             # named semaphore
-            is_mem = (fd in ["fmem", "fDEL"])
+            is_mem = fd in ["fmem", "fDEL"]
             if sys.platform == "darwin":
                 is_mem |= "n/loky-" in name
             if is_mem and "n/dev/shm/sem." in name:
                 named_sem += [name[1:]]
 
             # no other files should be opened at this stage in the process
-            assert (is_pipe or is_std or is_rng or is_mem)
+            assert is_pipe or is_std or is_rng or is_mem
 
         # there should be:
         # - one pipe for communication with main process
@@ -495,12 +511,14 @@ def _check_fds(self, pid, w):
         # - the Connection pipe
         # - additionally, on posix + Python 3.8: multiprocessing's
         #   resource_tracker pipe
-        if sys.version_info >= (3, 8) and os.name == 'posix':
+        if sys.version_info >= (3, 8) and os.name == "posix":
             n_expected_pipes = 4
         else:
             n_expected_pipes = 3
-        msg = ("Some pipes were not properly closed during the child process "
-               "setup.")
+        msg = (
+            "Some pipes were not properly closed during the child process "
+            "setup."
+        )
         assert n_pipe == n_expected_pipes, msg
 
         # assert that the writable part of the Pipe (not passed to child),
@@ -528,8 +546,10 @@ def test_sync_object_handling(self):
         with open(tmp_fname, "w"):
             # Process creating semaphore and pipes before stopping
             started, stop = self.Event(), self.Event()
-            p = self.Process(target=self._test_sync_object_handling,
-                             args=(started, stop, r, w.fileno()))
+            p = self.Process(
+                target=self._test_sync_object_handling,
+                args=(started, stop, r, w.fileno()),
+            )
             named_sem = []
             try:
 
@@ -557,7 +577,8 @@ def test_sync_object_handling(self):
                         if pid not in sem:
                             assert not os.path.exists(sem), (
                                 "Some named semaphore are not properly cleaned"
-                                " up")
+                                " up"
+                            )
 
                 assert p.exitcode == 0
 
@@ -578,49 +599,54 @@ def test_interactively_define_process_no_main(self, run_file):
         # when using -c option, we don't need the safeguard if __name__ ..
         # and thus test LokyProcess without the extra argument. For running
         # a script, it is necessary to use init_main_module=False.
-        code = '\n'.join([
-            'from loky.backend.process import LokyProcess',
-            'p = LokyProcess(target=id, args=(1,), ',
-            f'                init_main_module={not run_file})',
-            'p.start()',
-            'p.join()',
-            'msg = "LokyProcess failed to load without safeguard"',
-            'assert p.exitcode == 0, msg',
-            'print("ok")'
-        ])
+        code = "\n".join(
+            [
+                "from loky.backend.process import LokyProcess",
+                "p = LokyProcess(target=id, args=(1,), ",
+                f"                init_main_module={not run_file})",
+                "p.start()",
+                "p.join()",
+                'msg = "LokyProcess failed to load without safeguard"',
+                "assert p.exitcode == 0, msg",
+                'print("ok")',
+            ]
+        )
         cmd = [sys.executable]
         try:
             if run_file:
                 fid, filename = mkstemp(suffix="_joblib.py")
                 os.close(fid)
-                with open(filename, mode='w') as f:
+                with open(filename, mode="w") as f:
                     f.write(code)
                 cmd += [filename]
             else:
                 cmd += ["-c", code]
-            check_subprocess_call(cmd, stdout_regex='ok', timeout=10)
+            check_subprocess_call(cmd, stdout_regex="ok", timeout=10)
         finally:
             if run_file:
                 os.unlink(filename)
 
     def test_interactively_define_process_fail_main(self):
         # check that the default behavior of the LokyProcess is correct
-        code = '\n'.join([
-            'from loky.backend.process import LokyProcess',
-            'p = LokyProcess(target=id, args=(1,),',
-            '                init_main_module=True)',
-            'p.start()',
-            'p.join()',
-            'msg = "LokyProcess succeed without safeguards"',
-            'assert p.exitcode != 0, msg'
-        ])
+        code = "\n".join(
+            [
+                "from loky.backend.process import LokyProcess",
+                "p = LokyProcess(target=id, args=(1,),",
+                "                init_main_module=True)",
+                "p.start()",
+                "p.join()",
+                'msg = "LokyProcess succeed without safeguards"',
+                "assert p.exitcode != 0, msg",
+            ]
+        )
         fid, filename = mkstemp(suffix="_joblib.py")
         os.close(fid)
         try:
-            with open(filename, mode='w') as f:
+            with open(filename, mode="w") as f:
                 f.write(code)
-            stdout, stderr = check_subprocess_call([sys.executable, filename],
-                                                   timeout=10)
+            stdout, stderr = check_subprocess_call(
+                [sys.executable, filename], timeout=10
+            )
             if sys.platform == "win32":
                 assert "RuntimeError:" in stderr
             else:
@@ -644,24 +670,27 @@ def test_loky_get_context(self):
 
     def test_interactive_contex_no_main(self):
         # Ensure that loky context is working properly
-        code = '\n'.join([
-            'from loky.backend import get_context',
-            'ctx = get_context()',
-            'assert ctx.get_start_method() == "loky"',
-            'p = ctx.Process(target=id, args=(1,))',
-            'p.start()',
-            'p.join()',
-            'msg = "loky context failed to load without safeguard"',
-            'assert p.exitcode == 0, msg',
-            'print("ok")'
-        ])
+        code = "\n".join(
+            [
+                "from loky.backend import get_context",
+                "ctx = get_context()",
+                'assert ctx.get_start_method() == "loky"',
+                "p = ctx.Process(target=id, args=(1,))",
+                "p.start()",
+                "p.join()",
+                'msg = "loky context failed to load without safeguard"',
+                "assert p.exitcode == 0, msg",
+                'print("ok")',
+            ]
+        )
         try:
             fid, filename = mkstemp(suffix="_joblib.py")
             os.close(fid)
-            with open(filename, mode='w') as f:
+            with open(filename, mode="w") as f:
                 f.write(code)
-            check_subprocess_call([sys.executable, filename],
-                                  stdout_regex='ok', timeout=10)
+            check_subprocess_call(
+                [sys.executable, filename], stdout_regex="ok", timeout=10
+            )
         finally:
             os.unlink(filename)
 
@@ -674,8 +703,9 @@ def wait_for_handle(handle, timeout):
 
 def _run_nested_delayed(depth, delay, event):
     if depth > 0:
-        p = ctx_loky.Process(target=_run_nested_delayed,
-                             args=(depth - 1, delay, event))
+        p = ctx_loky.Process(
+            target=_run_nested_delayed, args=(depth - 1, delay, event)
+        )
         p.start()
         p.join()
     else:
@@ -694,8 +724,10 @@ def test_kill_process_tree(use_psutil):
     # Wait for all the processes to be launched
     if not event.wait(30):
         kill_process_tree(p, use_psutil=use_psutil)
-        raise RuntimeError("test_kill_process_tree was not able to launch "
-                           "all nested processes.")
+        raise RuntimeError(
+            "test_kill_process_tree was not able to launch "
+            "all nested processes."
+        )
 
     children = psutil.Process(pid=p.pid).children(recursive=True)
     kill_process_tree(p, use_psutil=use_psutil)
@@ -710,7 +742,7 @@ def _test_default_subcontext(queue):
     queue.put(mp.get_start_method())
 
 
-@pytest.mark.parametrize('method', START_METHODS)
+@pytest.mark.parametrize("method", START_METHODS)
 def test_default_subcontext(method):
     code = f"""if True:
         import sys
diff --git a/tests/test_loky_module.py b/tests/test_loky_module.py
index 7e641d9c..474f49dc 100644
--- a/tests/test_loky_module.py
+++ b/tests/test_loky_module.py
@@ -14,8 +14,9 @@
 
 
 def test_version():
-    assert hasattr(loky, '__version__'), (
-        "There are no __version__ argument on the loky module")
+    assert hasattr(
+        loky, "__version__"
+    ), "There are no __version__ argument on the loky module"
 
 
 def test_cpu_count():
@@ -33,16 +34,17 @@ def test_cpu_count():
     assert 1 <= cpus_physical <= cpus
 
 
-cpu_count_cmd = ("from loky.backend.context import cpu_count;"
-                 "print(cpu_count({args}))")
+cpu_count_cmd = (
+    "from loky.backend.context import cpu_count;" "print(cpu_count({args}))"
+)
 
 
 def test_cpu_count_os_sched_getaffinity():
-    if not hasattr(os, 'sched_getaffinity') or not hasattr(shutil, 'which'):
+    if not hasattr(os, "sched_getaffinity") or not hasattr(shutil, "which"):
         pytest.skip()
 
-    taskset_bin = shutil.which('taskset')
-    python_bin = shutil.which('python')
+    taskset_bin = shutil.which("taskset")
+    python_bin = shutil.which("python")
 
     if taskset_bin is None or python_bin is None:
         raise pytest.skip()
@@ -52,16 +54,32 @@ def test_cpu_count_os_sched_getaffinity():
     except NotImplementedError:
         pytest.skip()
 
-    res = check_output([taskset_bin, '-c', '0',
-                        python_bin, '-c', cpu_count_cmd.format(args='')],
-                       text=True)
-
-    res_physical = check_output([
-        taskset_bin, '-c', '0', python_bin, '-c',
-        cpu_count_cmd.format(args='only_physical_cores=True')], text=True)
-
-    assert res.strip() == '1'
-    assert res_physical.strip() == '1'
+    res = check_output(
+        [
+            taskset_bin,
+            "-c",
+            "0",
+            python_bin,
+            "-c",
+            cpu_count_cmd.format(args=""),
+        ],
+        text=True,
+    )
+
+    res_physical = check_output(
+        [
+            taskset_bin,
+            "-c",
+            "0",
+            python_bin,
+            "-c",
+            cpu_count_cmd.format(args="only_physical_cores=True"),
+        ],
+        text=True,
+    )
+
+    assert res.strip() == "1"
+    assert res_physical.strip() == "1"
 
 
 def test_cpu_count_psutil_affinity():
@@ -84,15 +102,17 @@ def test_cpu_count_cgroup_limit():
     if sys.platform == "win32":
         pytest.skip()
 
-    if not hasattr(shutil, 'which'):
+    if not hasattr(shutil, "which"):
         pytest.skip()
 
-    docker_bin = shutil.which('docker')
+    docker_bin = shutil.which("docker")
     if docker_bin is None:
         raise pytest.skip("docker is required to run this test")
 
     loky_module_path = os.path.abspath(os.path.dirname(loky.__file__))
-    loky_project_path = os.path.abspath(os.path.join(loky_module_path, os.pardir))
+    loky_project_path = os.path.abspath(
+        os.path.join(loky_module_path, os.pardir)
+    )
 
     # The following will always run using the Python 3.7 docker image.
     # We mount the loky source as /loky inside the container,
@@ -100,31 +120,40 @@ def test_cpu_count_cgroup_limit():
 
     # Tell docker to configure the Cgroup quota to use 0.5 CPU, loky will
     # always detect 1 CPU because it rounds up to the next integer.
-    res_500_mCPU = int(check_output(
-        f"{docker_bin} run --rm --cpus 0.5 -v {loky_project_path}:/loky python:3.10 "
-        f"/bin/bash -c 'pip install --quiet -e /loky ; "
-        f"python -c \"{cpu_count_cmd.format(args='')}\"'",
-        shell=True, text=True
-    ).strip())
+    res_500_mCPU = int(
+        check_output(
+            f"{docker_bin} run --rm --cpus 0.5 -v {loky_project_path}:/loky python:3.10 "
+            f"/bin/bash -c 'pip install --quiet -e /loky ; "
+            f"python -c \"{cpu_count_cmd.format(args='')}\"'",
+            shell=True,
+            text=True,
+        ).strip()
+    )
     assert res_500_mCPU == 1
 
     # Limiting to 1.5 CPUs can lead to 1 if there is only 1 CPU on the machine or
     # 2 if there are 2 CPUs or more.
-    res_1500_mCPU = int(check_output(
-        f"{docker_bin} run --rm --cpus 1.5 -v {loky_project_path}:/loky python:3.10 "
-        f"/bin/bash -c 'pip install --quiet -e /loky ; "
-        f"python -c \"{cpu_count_cmd.format(args='')}\"'",
-        shell=True, text=True
-    ).strip())
+    res_1500_mCPU = int(
+        check_output(
+            f"{docker_bin} run --rm --cpus 1.5 -v {loky_project_path}:/loky python:3.10 "
+            f"/bin/bash -c 'pip install --quiet -e /loky ; "
+            f"python -c \"{cpu_count_cmd.format(args='')}\"'",
+            shell=True,
+            text=True,
+        ).strip()
+    )
     assert res_1500_mCPU in (1, 2)
 
     # By default there is no limit: use all available CPUs.
-    res_default = int(check_output(
-        f"{docker_bin} run --rm -v {loky_project_path}:/loky python:3.10 "
-        f"/bin/bash -c 'pip install --quiet -e /loky ; "
-        f"python -c \"{cpu_count_cmd.format(args='')}\"'",
-        shell=True, text=True
-    ).strip())
+    res_default = int(
+        check_output(
+            f"{docker_bin} run --rm -v {loky_project_path}:/loky python:3.10 "
+            f"/bin/bash -c 'pip install --quiet -e /loky ; "
+            f"python -c \"{cpu_count_cmd.format(args='')}\"'",
+            shell=True,
+            text=True,
+        ).strip()
+    )
     assert res_default >= res_1500_mCPU
 
 
@@ -143,31 +172,33 @@ def test_only_physical_cores_error():
 
     with tempfile.TemporaryDirectory() as tmp_dir:
         # Write bad lscpu program
-        lscpu_path = f'{tmp_dir}/lscpu'
-        with open(lscpu_path, 'w') as f:
-            f.write("#!/bin/sh\n"
-                    "exit(1)")
+        lscpu_path = f"{tmp_dir}/lscpu"
+        with open(lscpu_path, "w") as f:
+            f.write("#!/bin/sh\n" "exit(1)")
         os.chmod(lscpu_path, 0o777)
 
         try:
-            old_path = os.environ['PATH']
-            os.environ['PATH'] = f'{tmp_dir}:{old_path}'
+            old_path = os.environ["PATH"]
+            os.environ["PATH"] = f"{tmp_dir}:{old_path}"
 
             # clear the cache otherwise the warning is not triggered
             import loky.backend.context
+
             loky.backend.context.physical_cores_cache = None
 
-            with pytest.warns(UserWarning, match="Could not find the number of"
-                                                 " physical cores"):
+            with pytest.warns(
+                UserWarning,
+                match="Could not find the number of" " physical cores",
+            ):
                 cpu_count(only_physical_cores=True)
 
             # Should not warn the second time
             with warnings.catch_warnings():
-                warnings.simplefilter('error')
+                warnings.simplefilter("error")
                 cpu_count(only_physical_cores=True)
 
         finally:
-            os.environ['PATH'] = old_path
+            os.environ["PATH"] = old_path
 
 
 def test_only_physical_cores_with_user_limitation():
diff --git a/tests/test_process_executor_forkserver.py b/tests/test_process_executor_forkserver.py
index 6dce76a8..8b5e0314 100644
--- a/tests/test_process_executor_forkserver.py
+++ b/tests/test_process_executor_forkserver.py
@@ -12,26 +12,30 @@
         AsCompletedTests,
         ExecutorShutdownTest,
         ExecutorTest,
-        WaitTests
+        WaitTests,
     )
 
     class ProcessPoolForkserverMixin(ExecutorMixin):
         executor_type = process_executor.ProcessPoolExecutor
-        context = get_context('forkserver')
+        context = get_context("forkserver")
 
-    class TestsProcessPoolForkserverShutdown(ProcessPoolForkserverMixin,
-                                             ExecutorShutdownTest):
+    class TestsProcessPoolForkserverShutdown(
+        ProcessPoolForkserverMixin, ExecutorShutdownTest
+    ):
         def _prime_executor(self):
             pass
 
-    class TestsProcessPoolForkserverWait(ProcessPoolForkserverMixin,
-                                         WaitTests):
+    class TestsProcessPoolForkserverWait(
+        ProcessPoolForkserverMixin, WaitTests
+    ):
         pass
 
-    class TestsProcessPoolForkserverAsCompleted(ProcessPoolForkserverMixin,
-                                                AsCompletedTests):
+    class TestsProcessPoolForkserverAsCompleted(
+        ProcessPoolForkserverMixin, AsCompletedTests
+    ):
         pass
 
-    class TestsProcessPoolForkserverExecutor(ProcessPoolForkserverMixin,
-                                             ExecutorTest):
+    class TestsProcessPoolForkserverExecutor(
+        ProcessPoolForkserverMixin, ExecutorTest
+    ):
         pass
diff --git a/tests/test_process_executor_loky.py b/tests/test_process_executor_loky.py
index a61f510d..e3ac21f7 100644
--- a/tests/test_process_executor_loky.py
+++ b/tests/test_process_executor_loky.py
@@ -2,8 +2,12 @@
 from loky.backend import get_context
 
 from ._executor_mixin import ExecutorMixin
-from ._test_process_executor import (AsCompletedTests, ExecutorShutdownTest,
-                                     ExecutorTest, WaitTests)
+from ._test_process_executor import (
+    AsCompletedTests,
+    ExecutorShutdownTest,
+    ExecutorTest,
+    WaitTests,
+)
 
 
 class ProcessPoolLokyMixin(ExecutorMixin):
@@ -12,22 +16,18 @@ class ProcessPoolLokyMixin(ExecutorMixin):
     context = get_context("loky")
 
 
-class TestsProcessPoolLokyShutdown(ProcessPoolLokyMixin,
-                                   ExecutorShutdownTest):
+class TestsProcessPoolLokyShutdown(ProcessPoolLokyMixin, ExecutorShutdownTest):
     def _prime_executor(self):
         pass
 
 
-class TestsProcessPoolLokyWait(ProcessPoolLokyMixin,
-                               WaitTests):
+class TestsProcessPoolLokyWait(ProcessPoolLokyMixin, WaitTests):
     pass
 
 
-class TestsProcessPoolLokyAsCompleted(ProcessPoolLokyMixin,
-                                      AsCompletedTests):
+class TestsProcessPoolLokyAsCompleted(ProcessPoolLokyMixin, AsCompletedTests):
     pass
 
 
-class TestsProcessPoolLokyExecutor(ProcessPoolLokyMixin,
-                                   ExecutorTest):
+class TestsProcessPoolLokyExecutor(ProcessPoolLokyMixin, ExecutorTest):
     pass
diff --git a/tests/test_process_executor_spawn.py b/tests/test_process_executor_spawn.py
index 8cc5a301..6d9e1de9 100644
--- a/tests/test_process_executor_spawn.py
+++ b/tests/test_process_executor_spawn.py
@@ -11,23 +11,25 @@
         AsCompletedTests,
         ExecutorShutdownTest,
         ExecutorTest,
-        WaitTests
+        WaitTests,
     )
 
     class ProcessPoolSpawnMixin(ExecutorMixin):
         executor_type = process_executor.ProcessPoolExecutor
-        context = get_context('spawn')
+        context = get_context("spawn")
 
-    class TestsProcessPoolSpawnShutdown(ProcessPoolSpawnMixin,
-                                        ExecutorShutdownTest):
+    class TestsProcessPoolSpawnShutdown(
+        ProcessPoolSpawnMixin, ExecutorShutdownTest
+    ):
         def _prime_executor(self):
             pass
 
     class TestsProcessPoolSpawnWait(ProcessPoolSpawnMixin, WaitTests):
         pass
 
-    class TestsProcessPoolSpawnAsCompleted(ProcessPoolSpawnMixin,
-                                           AsCompletedTests):
+    class TestsProcessPoolSpawnAsCompleted(
+        ProcessPoolSpawnMixin, AsCompletedTests
+    ):
         pass
 
     class TestsProcessPoolSpawnExecutor(ProcessPoolSpawnMixin, ExecutorTest):
diff --git a/tests/test_resource_tracker.py b/tests/test_resource_tracker.py
index 4bd5fa70..42e87afb 100644
--- a/tests/test_resource_tracker.py
+++ b/tests/test_resource_tracker.py
@@ -28,7 +28,6 @@ def get_rtracker_pid():
 
 
 class TestResourceTracker:
-
     @pytest.mark.parametrize("rtype", ["file", "folder", "semlock"])
     def test_resource_utils(self, rtype):
         # Check that the resouce utils work as expected in the main process
@@ -50,7 +49,7 @@ def test_child_retrieves_resource_tracker(self):
         # Register a resource in the parent process, and un-register it in the
         # child process. If the two processes do not share the same
         # resource_tracker, a cache KeyError should be printed in stderr.
-        cmd = '''if 1:
+        cmd = """if 1:
         import os, sys
 
         from loky import ProcessPoolExecutor
@@ -76,11 +75,13 @@ def maybe_unlink(name, rtype):
         e = ProcessPoolExecutor(1)
         e.submit(maybe_unlink, filename, "file").result()
         e.shutdown()
-        '''
+        """
         try:
-            p = subprocess.run([sys.executable, '-E', '-c', cmd],
-                               capture_output=True,
-                               text=True)
+            p = subprocess.run(
+                [sys.executable, "-E", "-c", cmd],
+                capture_output=True,
+                text=True,
+            )
             filename = p.stdout.strip()
 
             pattern = f"decremented refcount of file {filename}"
@@ -102,7 +103,7 @@ def test_resource_tracker(self, rtype):
         if (sys.platform == "win32") and rtype == "semlock":
             pytest.skip("no semlock on windows")
 
-        cmd = f'''if 1:
+        cmd = f"""if 1:
             import time, os, tempfile, sys
             from loky.backend import resource_tracker
             from utils import create_resource
@@ -115,13 +116,15 @@ def test_resource_tracker(self, rtype):
                 sys.stdout.write(f"{{rname}}\\n")
                 sys.stdout.flush()
             time.sleep(10)
-        '''
-        env = {**os.environ, 'PYTHONPATH': os.path.dirname(__file__)}
-        p = subprocess.Popen([sys.executable, '-c', cmd],
-                             stderr=subprocess.PIPE,
-                             stdout=subprocess.PIPE,
-                             env=env,
-                             text=True)
+        """
+        env = {**os.environ, "PYTHONPATH": os.path.dirname(__file__)}
+        p = subprocess.Popen(
+            [sys.executable, "-c", cmd],
+            stderr=subprocess.PIPE,
+            stdout=subprocess.PIPE,
+            env=env,
+            text=True,
+        )
         name1 = p.stdout.readline().rstrip()
         name2 = p.stdout.readline().rstrip()
 
@@ -142,13 +145,13 @@ def test_resource_tracker(self, rtype):
         p.stderr.close()
         p.stdout.close()
 
-        expected = f'resource_tracker: There appear to be 2 leaked {rtype}'
+        expected = f"resource_tracker: There appear to be 2 leaked {rtype}"
         assert re.search(expected, err) is not None
 
         # resource 1 is still registered, but was destroyed externally: the
         # tracker is expected to complain.
         if sys.platform == "win32":
-            errno_map = {'file': 2, 'folder': 3}
+            errno_map = {"file": 2, "folder": 3}
             expected = (
                 f"resource_tracker: {re.escape(name1)}: "
                 f"(WindowsError\\(({errno_map[rtype]})|FileNotFoundError)"
@@ -165,7 +168,7 @@ def test_resource_tracker_refcounting(self, rtype):
         if sys.platform == "win32" and rtype == "semlock":
             pytest.skip("no semlock on windows")
 
-        cmd = f'''if 1:
+        cmd = f"""if 1:
         import os
         import tempfile
         import time
@@ -208,18 +211,19 @@ def test_resource_tracker_refcounting(self, rtype):
             except NameError:
                 # "name" is not defined because create_resource has failed
                 pass
-        '''
+        """
 
-        env = {**os.environ, 'PYTHONPATH': os.path.dirname(__file__)}
-        p = subprocess.run([sys.executable, '-c', cmd],
-                           capture_output=True,
-                           env=env)
+        env = {**os.environ, "PYTHONPATH": os.path.dirname(__file__)}
+        p = subprocess.run(
+            [sys.executable, "-c", cmd], capture_output=True, env=env
+        )
         assert p.returncode == 0, p.stderr
 
     def check_resource_tracker_death(self, signum, should_die):
         # bpo-31310: if the semaphore tracker process has died, it should
         # be restarted implicitly.
         from loky.backend.resource_tracker import _resource_tracker
+
         pid = _resource_tracker._pid
         if pid is not None:
             os.kill(pid, signal.SIGKILL)
@@ -238,7 +242,8 @@ def check_resource_tracker_death(self, signum, should_die):
 
             # remove unrelated MacOS warning messages first
             warnings.filterwarnings(
-                "ignore", message='semaphore are broken on OSX')
+                "ignore", message="semaphore are broken on OSX"
+            )
 
             sem = ctx.Semaphore()
             sem.acquire()
@@ -254,32 +259,38 @@ def check_resource_tracker_death(self, signum, should_die):
                 the_warn = all_warn[0]
                 assert issubclass(the_warn.category, UserWarning)
                 assert "resource_tracker: process died" in str(
-                    the_warn.message)
+                    the_warn.message
+                )
             else:
                 assert len(all_warn) == 0
 
-    @pytest.mark.skipif(sys.platform == "win32",
-                        reason="Limited signal support on Windows")
+    @pytest.mark.skipif(
+        sys.platform == "win32", reason="Limited signal support on Windows"
+    )
     def test_resource_tracker_sigint(self):
         # Catchable signal (ignored by resource tracker)
         self.check_resource_tracker_death(signal.SIGINT, False)
 
-    @pytest.mark.skipif(sys.platform == "win32",
-                        reason="Limited signal support on Windows")
+    @pytest.mark.skipif(
+        sys.platform == "win32", reason="Limited signal support on Windows"
+    )
     def test_resource_tracker_sigterm(self):
         # Catchable signal (ignored by resource tracker)
         self.check_resource_tracker_death(signal.SIGTERM, False)
 
-    @pytest.mark.skipif(sys.platform == "win32",
-                        reason="Limited signal support on Windows")
+    @pytest.mark.skipif(
+        sys.platform == "win32", reason="Limited signal support on Windows"
+    )
     def test_resource_tracker_sigkill(self):
         # Uncatchable signal.
         self.check_resource_tracker_death(signal.SIGKILL, True)
 
-    @pytest.mark.skipif(sys.version_info < (3, 8),
-                        reason="SharedMemory introduced in Python 3.8")
+    @pytest.mark.skipif(
+        sys.version_info < (3, 8),
+        reason="SharedMemory introduced in Python 3.8",
+    )
     def test_loky_process_inherit_multiprocessing_resource_tracker(self):
-        cmd = '''if 1:
+        cmd = """if 1:
         from loky import get_reusable_executor
         from multiprocessing.shared_memory import SharedMemory
         from multiprocessing.resource_tracker import (
@@ -310,8 +321,9 @@ def mp_rtracker_getattrs():
             shm = SharedMemory(create=True, size=10)
             f = executor.submit(shm.unlink).result()
 
-        '''
-        p = subprocess.run([sys.executable, '-c', cmd],
-                           capture_output=True, text=True)
+        """
+        p = subprocess.run(
+            [sys.executable, "-c", cmd], capture_output=True, text=True
+        )
         assert not p.stdout
         assert not p.stderr
diff --git a/tests/test_reusable_executor.py b/tests/test_reusable_executor.py
index fdd98269..10a19dbc 100644
--- a/tests/test_reusable_executor.py
+++ b/tests/test_reusable_executor.py
@@ -35,10 +35,12 @@
 # Compat windows
 if sys.platform == "win32":
     from signal import SIGTERM as SIGKILL
+
     libc = ctypes.cdll.msvcrt
 else:
     from signal import SIGKILL
     from ctypes.util import find_library
+
     libc = ctypes.CDLL(find_library("c"))
 
 
@@ -72,6 +74,7 @@ def wait_dead(worker, n_tries=1000, delay=0.001):
 def crash():
     """Induces a segfault"""
     import faulthandler
+
     faulthandler._sigsegv()
 
 
@@ -135,42 +138,49 @@ def do_nothing(arg):
 
 class CrashAtPickle:
     """Bad object that triggers a segfault at pickling time."""
+
     def __reduce__(self):
         crash()
 
 
 class CrashAtUnpickle:
     """Bad object that triggers a segfault at unpickling time."""
+
     def __reduce__(self):
         return crash, ()
 
 
 class ExitAtPickle:
     """Bad object that triggers a segfault at pickling time."""
+
     def __reduce__(self):
         exit()
 
 
 class ExitAtUnpickle:
     """Bad object that triggers a process exit at unpickling time."""
+
     def __reduce__(self):
         return exit, ()
 
 
 class CExitAtPickle:
     """Bad object that triggers a segfault at pickling time."""
+
     def __reduce__(self):
         c_exit()
 
 
 class CExitAtUnpickle:
     """Bad object that triggers a process exit at unpickling time."""
+
     def __reduce__(self):
         return c_exit, ()
 
 
 class ErrorAtPickle:
     """Bad object that raises an error at pickling time."""
+
     def __init__(self, fail=True):
         self.fail = fail
 
@@ -178,12 +188,13 @@ def __reduce__(self):
         if self.fail:
             raise PicklingError("Error in pickle")
         else:
-            return id, (42, )
+            return id, (42,)
 
 
 class ErrorAtUnpickle:
     """Bad object that triggers a process exit at unpickling time."""
-    def __init__(self, etype=UnpicklingError, message='the error message'):
+
+    def __init__(self, etype=UnpicklingError, message="the error message"):
         self.etype = etype
         self.message = message
 
@@ -193,6 +204,7 @@ def __reduce__(self):
 
 class CrashAtGCInWorker:
     """Bad object that triggers a segfault at call item GC time"""
+
     def __del__(self):
         if current_process().name != "MainProcess":
             crash()
@@ -200,6 +212,7 @@ def __del__(self):
 
 class CExitAtGCInWorker:
     """Exit worker at call item GC time"""
+
     def __del__(self):
         if current_process().name != "MainProcess":
             c_exit()
@@ -225,14 +238,22 @@ class TestExecutorDeadLock(ReusableExecutorMixin):
         # on workers
         (return_instance, (CrashAtPickle,), TerminatedWorkerError, "SIGSEGV"),
         (return_instance, (ExitAtPickle,), SystemExit, None),
-        (return_instance, (CExitAtPickle,), TerminatedWorkerError,
-         r"EXIT\(0\)"),
+        (
+            return_instance,
+            (CExitAtPickle,),
+            TerminatedWorkerError,
+            r"EXIT\(0\)",
+        ),
         (return_instance, (ErrorAtPickle,), PicklingError, None),
         # Check problem occuring while unpickling a task in
         # the result_handler thread
         (return_instance, (ExitAtUnpickle,), BrokenProcessPool, "SystemExit"),
-        (return_instance, (ErrorAtUnpickle,), BrokenProcessPool,
-         "UnpicklingError"),
+        (
+            return_instance,
+            (ErrorAtUnpickle,),
+            BrokenProcessPool,
+            "UnpicklingError",
+        ),
     ]
 
     @pytest.mark.parametrize("func, args, expected_err, match", crash_cases)
@@ -255,14 +276,16 @@ def test_crashes(self, func, args, expected_err, match):
                 raise exc_info.value.__cause__
 
     @pytest.mark.parametrize("func, args, expected_err, match", crash_cases)
-    def test_in_callback_submit_with_crash(self, func, args, expected_err,
-                                           match):
+    def test_in_callback_submit_with_crash(
+        self, func, args, expected_err, match
+    ):
         """Test the recovery from callback crash"""
         executor = get_reusable_executor(max_workers=2, timeout=12)
 
         def in_callback_submit(future):
-            future2 = get_reusable_executor(
-                max_workers=2, timeout=12).submit(func, *args)
+            future2 = get_reusable_executor(max_workers=2, timeout=12).submit(
+                func, *args
+            )
             # Store the future of the job submitted in the callback to make it
             # easy to introspect.
             future.callback_future = future2
@@ -277,7 +300,7 @@ def in_callback_submit(future):
         f.add_done_callback(in_callback_submit)
         assert f.result() == 42
         if not f.callback_done.wait(timeout=3):
-            raise AssertionError('callback not done before timeout')
+            raise AssertionError("callback not done before timeout")
 
         match_err = None
         if expected_err is TerminatedWorkerError:
@@ -314,7 +337,7 @@ def test_callback_crash_on_submit(self):
         f = executor.submit(id_sleep, 42, delay)
         f.add_done_callback(lambda _: raise_error())
         assert f.result() == 42
-        assert executor.submit(id_sleep, 42, 0.).result() == 42
+        assert executor.submit(id_sleep, 42, 0.0).result() == 42
 
     def test_deadlock_kill(self):
         """Test deadlock recovery for reusable_executor"""
@@ -325,31 +348,37 @@ def test_deadlock_kill(self):
         with pytest.warns(UserWarning) as recorded_warnings:
             executor = get_reusable_executor(max_workers=2, timeout=None)
         assert len(recorded_warnings) == 1
-        expected_msg = ("Trying to resize an executor with running jobs:"
-                        " waiting for jobs completion before resizing.")
+        expected_msg = (
+            "Trying to resize an executor with running jobs:"
+            " waiting for jobs completion before resizing."
+        )
         assert recorded_warnings[0].message.args[0] == expected_msg
         os.kill(worker.pid, SIGKILL)
         wait_dead(worker)
 
         # wait for the executor to be able to detect the issue and set itself
         # in broken state:
-        sleep(.5)
-        with pytest.raises(TerminatedWorkerError,
-                           match=filter_match("SIGKILL")):
+        sleep(0.5)
+        with pytest.raises(
+            TerminatedWorkerError, match=filter_match("SIGKILL")
+        ):
             executor.submit(id_sleep, 42, 0.1).result()
 
         # the get_reusable_executor factory should be able to create a new
         # working instance
         executor = get_reusable_executor(max_workers=2, timeout=None)
-        assert executor.submit(id_sleep, 42, 0.).result() == 42
+        assert executor.submit(id_sleep, 42, 0.0).result() == 42
 
     @pytest.mark.parametrize("n_proc", [1, 2, 5, 13])
     def test_crash_races(self, n_proc):
         """Test the race conditions in reusable_executor crash handling"""
         pytest.importorskip("psutil")  # required for kill_friend & co
 
-        if (sys.platform == 'win32' and sys.version_info >= (3, 8)
-                and n_proc > 5):
+        if (
+            sys.platform == "win32"
+            and sys.version_info >= (3, 8)
+            and n_proc > 5
+        ):
             pytest.skip(
                 "On win32, the paging size can be too small to import numpy "
                 "multiple times in the sub-processes (imported when loading "
@@ -364,12 +393,14 @@ def test_crash_races(self, n_proc):
         pids = list(executor._processes.keys())
         assert len(pids) == n_proc
         assert None not in pids
-        res = executor.map(sleep_then_check_pids_exist,
-                           [(.0001 * (j // 2), pids)
-                            for j in range(2 * n_proc)])
+        res = executor.map(
+            sleep_then_check_pids_exist,
+            [(0.0001 * (j // 2), pids) for j in range(2 * n_proc)],
+        )
         assert all(res)
-        with pytest.raises(TerminatedWorkerError,
-                           match=filter_match("SIGKILL")):
+        with pytest.raises(
+            TerminatedWorkerError, match=filter_match("SIGKILL")
+        ):
             res = executor.map(kill_friend, pids[::-1])
             list(res)
 
@@ -378,19 +409,22 @@ def test_imap_handle_iterable_exception(self):
         # builded version of python
         executor = get_reusable_executor(max_workers=2)
         with pytest.raises(SayWhenError):
-            executor.map(id_sleep, exception_throwing_generator(10, 3),
-                         chunksize=1)
+            executor.map(
+                id_sleep, exception_throwing_generator(10, 3), chunksize=1
+            )
 
         # SayWhenError seen at start of problematic chunk's results
         executor = get_reusable_executor(max_workers=2)
         with pytest.raises(SayWhenError):
-            executor.map(id_sleep, exception_throwing_generator(20, 7),
-                         chunksize=2)
+            executor.map(
+                id_sleep, exception_throwing_generator(20, 7), chunksize=2
+            )
 
         executor = get_reusable_executor(max_workers=2)
         with pytest.raises(SayWhenError):
-            executor.map(id_sleep, exception_throwing_generator(20, 7),
-                         chunksize=4)
+            executor.map(
+                id_sleep, exception_throwing_generator(20, 7), chunksize=4
+            )
 
     def test_queue_full_deadlock(self):
         with warnings.catch_warnings():
@@ -399,23 +433,27 @@ def test_queue_full_deadlock(self):
             executor = get_reusable_executor(max_workers=1)
             executor.submit(id, 42)
 
-        fs_fail = [executor.submit(do_nothing, ErrorAtPickle(True))
-                   for _ in range(100)]
-        fs = [executor.submit(do_nothing, ErrorAtPickle(False))
-              for _ in range(100)]
+        fs_fail = [
+            executor.submit(do_nothing, ErrorAtPickle(True))
+            for _ in range(100)
+        ]
+        fs = [
+            executor.submit(do_nothing, ErrorAtPickle(False))
+            for _ in range(100)
+        ]
         with pytest.raises(PicklingError):
             fs_fail[99].result()
         assert fs[99].result()
 
     def test_informative_error_when_fail_at_unpickle(self):
         executor = get_reusable_executor(max_workers=2)
-        obj = ErrorAtUnpickle(RuntimeError, 'message raised in child')
+        obj = ErrorAtUnpickle(RuntimeError, "message raised in child")
         f = executor.submit(id, obj)
 
         with pytest.raises(BrokenProcessPool) as exc_info:
             f.result()
-        assert 'RuntimeError' in str(exc_info.value.__cause__)
-        assert 'message raised in child' in str(exc_info.value.__cause__)
+        assert "RuntimeError" in str(exc_info.value.__cause__)
+        assert "message raised in child" in str(exc_info.value.__cause__)
 
     @pytest.mark.skipif(np is None, reason="requires numpy")
     def test_numpy_dot_parent_and_child_no_freeze(self):
@@ -430,12 +468,12 @@ def test_numpy_dot_parent_and_child_no_freeze(self):
 
 
 class TestTerminateExecutor(ReusableExecutorMixin):
-
     def test_shutdown_kill(self):
         """Test reusable_executor termination handling"""
         from itertools import repeat
+
         executor = get_reusable_executor(max_workers=5)
-        res1 = executor.map(id_sleep, range(100), repeat(.001))
+        res1 = executor.map(id_sleep, range(100), repeat(0.001))
         res2 = executor.map(id_sleep, range(100), repeat(1))
         assert list(res1) == list(range(100))
 
@@ -455,9 +493,10 @@ def test_shutdown_deadlock(self):
         # Test the executor.shutdown call do not cause deadlock
         executor = get_reusable_executor(max_workers=2, timeout=None)
         executor.map(id, range(2))  # start the worker processes
-        executor.submit(kill_friend, (next(iter(executor._processes.keys())),
-                                      .0))
-        sleep(.01)
+        executor.submit(
+            kill_friend, (next(iter(executor._processes.keys())), 0.0)
+        )
+        sleep(0.01)
         executor.shutdown(wait=True)
 
     def test_kill_workers_on_new_options(self):
@@ -468,15 +507,18 @@ def test_kill_workers_on_new_options(self):
         # change the constructor parameter while requesting not to wait
         # for the long running task to complete (the workers will get
         # shutdown forcibly)
-        executor = get_reusable_executor(max_workers=2, timeout=5,
-                                         kill_workers=True)
+        executor = get_reusable_executor(
+            max_workers=2, timeout=5, kill_workers=True
+        )
         with pytest.raises(ShutdownExecutorError):
             f.result()
         f2 = executor.submit(id_sleep, 42, 0)
         assert f2.result() == 42
 
-    @pytest.mark.parametrize("bad_object, match", [
-        (CrashAtGCInWorker, "SIGSEGV"), (CExitAtGCInWorker, r"EXIT\(0\)")])
+    @pytest.mark.parametrize(
+        "bad_object, match",
+        [(CrashAtGCInWorker, "SIGSEGV"), (CExitAtGCInWorker, r"EXIT\(0\)")],
+    )
     def test_call_item_gc_crash_or_exit(self, bad_object, match):
         executor = get_reusable_executor(max_workers=1)
         bad_object = bad_object()
@@ -490,7 +532,7 @@ def test_call_item_gc_crash_or_exit(self, bad_object, match):
         # when processing subsequently dispatched tasks:
         with pytest.raises(TerminatedWorkerError, match=filter_match(match)):
             executor.submit(gc.collect).result()
-            for _ in executor.map(sleep, [.1] * 100):
+            for _ in executor.map(sleep, [0.1] * 100):
                 pass
 
     def test_sigkill_shutdown_leaks_workers(self):
@@ -510,8 +552,9 @@ def test_sigkill_shutdown_leaks_workers(self):
             print(f'parent_pid:{parent_pid}')
             psutil.Process(os.getpid()).kill()
         """
-        with NamedTemporaryFile(mode='w', suffix="_joblib.py",
-                                delete=True) as f:
+        with NamedTemporaryFile(
+            mode="w", suffix="_joblib.py", delete=True
+        ) as f:
             f.write(code)
             f.flush()
             cmd = [sys.executable, f.name]
@@ -520,19 +563,20 @@ def test_sigkill_shutdown_leaks_workers(self):
                 stdout=subprocess.PIPE,
                 stderr=subprocess.STDOUT,
                 text=True,
-                timeout=60
+                timeout=60,
             )
             running_workers = []
-            for line in out.stdout.split('\n'):
-                if line.startswith('worker_pid'):
-                    worker_pid = int(line.split(':')[1])
+            for line in out.stdout.split("\n"):
+                if line.startswith("worker_pid"):
+                    worker_pid = int(line.split(":")[1])
                     try:
                         psutil.Process(worker_pid)
                         running_workers.append(worker_pid)
                     except psutil.NoSuchProcess:
                         pass
-            assert not len(running_workers), (
-                f'There are running workers left: {running_workers}')
+            assert not len(
+                running_workers
+            ), f"There are running workers left: {running_workers}"
 
 
 class TestResizeExecutor(ReusableExecutorMixin):
@@ -548,7 +592,7 @@ def test_reusable_executor_resize(self):
         # the old one as it is still in a good shape. The resize should not
         # occur while there are on going works.
         pids = list(executor._processes.keys())
-        res1 = executor.submit(sleep_then_check_pids_exist, (.3, pids))
+        res1 = executor.submit(sleep_then_check_pids_exist, (0.3, pids))
         clean_warning_registry()
         with warnings.catch_warnings(record=True) as w:
             # Cause all warnings to always be triggered.
@@ -557,8 +601,9 @@ def test_reusable_executor_resize(self):
             assert len(w) == 1
             expected_msg = "Trying to resize an executor with running jobs"
             assert expected_msg in str(w[0].message)
-            assert res1.result(), ("Resize should wait for current processes "
-                                   " to finish")
+            assert res1.result(), (
+                "Resize should wait for current processes " " to finish"
+            )
             assert len(executor._processes) == 1
             assert next(iter(executor._processes.keys())) in pids
 
@@ -582,9 +627,9 @@ def test_reusable_executor_resize_many_times(self, kill_workers, reuse):
         # Tentative non-regression test for a deadlock when shutting down
         # the workers of an executor prior to resizing it.
         kwargs = {
-            'timeout': None,
-            'kill_workers': kill_workers,
-            'reuse': reuse,
+            "timeout": None,
+            "kill_workers": kill_workers,
+            "reuse": reuse,
         }
         with warnings.catch_warnings(record=True):
             # Cause all warnings to always be triggered.
@@ -603,37 +648,38 @@ def test_kill_after_resize_call(self):
         executor = get_reusable_executor(max_workers=2, timeout=None)
         executor.map(id, range(2))  # trigger the creation of worker processes
         pid = next(iter(executor._processes.keys()))
-        executor.submit(kill_friend, (pid, .1))
+        executor.submit(kill_friend, (pid, 0.1))
 
         with pytest.warns(UserWarning) as recorded_warnings:
             warnings.simplefilter("always")
             executor = get_reusable_executor(max_workers=1, timeout=None)
         assert len(recorded_warnings) == 1
-        expected_msg = ("Trying to resize an executor with running jobs:"
-                        " waiting for jobs completion before resizing.")
+        expected_msg = (
+            "Trying to resize an executor with running jobs:"
+            " waiting for jobs completion before resizing."
+        )
         assert recorded_warnings[0].message.args[0] == expected_msg
-        assert executor.submit(id_sleep, 42, 0.).result() == 42
+        assert executor.submit(id_sleep, 42, 0.0).result() == 42
         executor.shutdown()
 
     def test_resize_after_timeout(self):
         with warnings.catch_warnings(record=True) as recorded_warnings:
             warnings.simplefilter("always")
-            executor = get_reusable_executor(max_workers=2, timeout=.001)
-            assert executor.submit(id_sleep, 42, 0.).result() == 42
-            sleep(.1)
-            executor = get_reusable_executor(max_workers=8, timeout=.001)
-            assert executor.submit(id_sleep, 42, 0.).result() == 42
-            sleep(.1)
-            executor = get_reusable_executor(max_workers=2, timeout=.001)
-            assert executor.submit(id_sleep, 42, 0.).result() == 42
+            executor = get_reusable_executor(max_workers=2, timeout=0.001)
+            assert executor.submit(id_sleep, 42, 0.0).result() == 42
+            sleep(0.1)
+            executor = get_reusable_executor(max_workers=8, timeout=0.001)
+            assert executor.submit(id_sleep, 42, 0.0).result() == 42
+            sleep(0.1)
+            executor = get_reusable_executor(max_workers=2, timeout=0.001)
+            assert executor.submit(id_sleep, 42, 0.0).result() == 42
 
         if len(recorded_warnings) > 1:
-            expected_msg = 'A worker stopped'
+            expected_msg = "A worker stopped"
             assert expected_msg in recorded_warnings[0].message.args[0]
 
 
 class TestGetReusableExecutor(ReusableExecutorMixin):
-
     def test_invalid_process_number(self):
         """Raise error on invalid process number"""
 
@@ -656,11 +702,11 @@ def test_invalid_context(self):
                 get_reusable_executor(max_workers=2, context="fork")
 
     def test_pass_start_method_name_as_context(self):
-        executor = get_reusable_executor(max_workers=2, context='loky')
+        executor = get_reusable_executor(max_workers=2, context="loky")
         assert executor.submit(id, 42).result() >= 0
 
         with pytest.raises(ValueError):
-            get_reusable_executor(max_workers=2, context='bad_start_method')
+            get_reusable_executor(max_workers=2, context="bad_start_method")
 
     def test_interactively_defined_executor_no_main(self):
         # check that the init_main_module parameter works properly
@@ -690,9 +736,11 @@ def test_reused_flag(self):
         )
         assert not reused
 
-    @pytest.mark.xfail(cloudpickle_version >= Version("0.5.4") and
-                       cloudpickle_version <= Version("0.7.0"),
-                       reason="Known issue in cloudpickle")
+    @pytest.mark.xfail(
+        cloudpickle_version >= Version("0.5.4")
+        and cloudpickle_version <= Version("0.7.0"),
+        reason="Known issue in cloudpickle",
+    )
     # https://github.com/cloudpipe/cloudpickle/pull/240
     def test_interactively_defined_nested_functions(self):
         # Check that it's possible to call nested interactively defined
@@ -807,7 +855,7 @@ def test_compat_with_concurrent_futures_exception(self):
         # It should be possible to use a loky process pool executor as a dropin
         # replacement for a ProcessPoolExecutor, including when catching
         # exceptions:
-        concurrent = pytest.importorskip('concurrent')
+        concurrent = pytest.importorskip("concurrent")
         from concurrent.futures.process import BrokenProcessPool as BPPExc
 
         with pytest.raises(BPPExc):
@@ -822,55 +870,62 @@ def test_compat_with_concurrent_futures_exception(self):
         assert len(running) == 0
 
     thread_configurations = [
-        ('constant', 'clean_start'),
-        ('constant', 'broken_start'),
-        ('varying', 'clean_start'),
-        ('varying', 'broken_start'),
+        ("constant", "clean_start"),
+        ("constant", "broken_start"),
+        ("varying", "clean_start"),
+        ("varying", "broken_start"),
     ]
 
     @pytest.mark.parametrize("workers, executor_state", thread_configurations)
     def test_reusable_executor_thread_safety(self, workers, executor_state):
-        if executor_state == 'clean_start':
+        if executor_state == "clean_start":
             # Create a new shared executor and ensures that it's workers are
             # ready:
             get_reusable_executor(reuse=False).submit(id, 42).result()
         else:
             # Break the shared executor before launching the threads:
-            with pytest.raises(TerminatedWorkerError,
-                               match=filter_match("SIGSEGV")):
+            with pytest.raises(
+                TerminatedWorkerError, match=filter_match("SIGSEGV")
+            ):
                 executor = get_reusable_executor(reuse=False)
                 executor.submit(return_instance, CrashAtPickle).result()
 
-        def helper_func(output_collector, max_workers=2, n_outer_steps=5,
-                        n_inner_steps=10):
+        def helper_func(
+            output_collector, max_workers=2, n_outer_steps=5, n_inner_steps=10
+        ):
             with warnings.catch_warnings():  # ignore resize warnings
                 warnings.simplefilter("always")
                 executor = get_reusable_executor(max_workers=max_workers)
                 for _ in range(n_outer_steps):
                     results = executor.map(
-                        lambda x: x ** 2, range(n_inner_steps))
-                    expected_result = [x ** 2 for x in range(n_inner_steps)]
+                        lambda x: x**2, range(n_inner_steps)
+                    )
+                    expected_result = [x**2 for x in range(n_inner_steps)]
                     assert list(results) == expected_result
-                output_collector.append('ok')
+                output_collector.append("ok")
 
-        if workers == 'constant':
+        if workers == "constant":
             max_workers = [2] * 10
         else:
             max_workers = [(i % 4) + 1 for i in range(10)]
         # Use the same executor with the same number of workers concurrently
         # in different threads:
         output_collector = []
-        threads = [threading.Thread(
-            target=helper_func, args=(output_collector, w),
-            name=f'test_thread_{i:02d}_max_workers_{w:d}')
-            for i, w in enumerate(max_workers)]
+        threads = [
+            threading.Thread(
+                target=helper_func,
+                args=(output_collector, w),
+                name=f"test_thread_{i:02d}_max_workers_{w:d}",
+            )
+            for i, w in enumerate(max_workers)
+        ]
 
         with warnings.catch_warnings(record=True):
             for t in threads:
                 t.start()
             for t in threads:
                 t.join()
-        assert output_collector == ['ok'] * len(threads)
+        assert output_collector == ["ok"] * len(threads)
 
     def test_reusable_executor_reuse_true(self):
         executor = get_reusable_executor(max_workers=3, timeout=42)
@@ -904,25 +959,27 @@ def _test_initializer(self, delay=0):
 
     def test_reusable_initializer(self):
         executor = get_reusable_executor(
-            max_workers=2, initializer=self._initializer, initargs=('done',))
+            max_workers=2, initializer=self._initializer, initargs=("done",)
+        )
 
-        assert executor.submit(self._test_initializer).result() == 'done'
+        assert executor.submit(self._test_initializer).result() == "done"
 
         # when the initializer change, the executor is re-spawned
         executor = get_reusable_executor(
-            max_workers=2, initializer=self._initializer, initargs=(42,))
+            max_workers=2, initializer=self._initializer, initargs=(42,)
+        )
 
         assert executor.submit(self._test_initializer).result() == 42
 
         # With reuse=True, the executor use the same initializer
         executor = get_reusable_executor(max_workers=4, reuse=True)
-        for x in executor.map(self._test_initializer, delay=.1):
+        for x in executor.map(self._test_initializer, delay=0.1):
             assert x == 42
 
         # With reuse='auto', the initializer is not used anymore
         executor = get_reusable_executor(max_workers=4)
-        for x in executor.map(self._test_initializer, delay=.1):
-            assert x == 'uninitialized'
+        for x in executor.map(self._test_initializer, delay=0.1):
+            assert x == "uninitialized"
 
     # XXX: not sure if #369 has been fixed or not. Let's not make it XFAIL
     # for now to see if it is still flaky on CI.
@@ -930,7 +987,7 @@ def test_reusable_initializer(self):
     def test_error_in_nested_call_keeps_resource_tracker_silent(self):
         # Safety smoke test: test that nested parallel calls don't yield noisy
         # resource_tracker outputs when the grandchild errors out.
-        cmd = '''if 1:
+        cmd = """if 1:
             from loky import get_reusable_executor
 
 
@@ -945,9 +1002,12 @@ def nested_loop(f):
 
             executor = get_reusable_executor(max_workers=2)
             list(executor.map(nested_loop, [raise_error])
-        '''
-        p = subprocess.Popen([sys.executable, '-c', cmd],
-                            stderr=subprocess.PIPE, stdout=subprocess.PIPE)
+        """
+        p = subprocess.Popen(
+            [sys.executable, "-c", cmd],
+            stderr=subprocess.PIPE,
+            stdout=subprocess.PIPE,
+        )
         p.wait()
         out, err = p.communicate()
         assert p.returncode == 1, out.decode()
diff --git a/tests/test_synchronize.py b/tests/test_synchronize.py
index a83a0ed5..1ceaa01c 100644
--- a/tests/test_synchronize.py
+++ b/tests/test_synchronize.py
@@ -12,8 +12,8 @@
 loky_context = get_context("loky")
 
 DELTA = 0.1
-TIMEOUT1 = .1
-TIMEOUT2 = .3
+TIMEOUT1 = 0.1
+TIMEOUT2 = 0.3
 
 
 @pytest.mark.skipif(sys.platform == "win32", reason="UNIX test")
@@ -52,7 +52,6 @@ def assert_timing_almost_equal(t1, t2=0):
 
 
 class TestLock:
-
     def test_lock(self):
         lock = loky_context.Lock()
         assert lock.acquire()
@@ -82,7 +81,6 @@ def test_lock_context(self):
 
 
 class TestSemaphore:
-
     def _test_semaphore(self, sem):
         assert_sem_value_equal(sem, 2)
         assert sem.acquire()
@@ -104,8 +102,9 @@ def test_semaphore(self):
         assert sem.release() is None
         assert_sem_value_equal(sem, 4)
 
-    @pytest.mark.skipif(sys.platform == "darwin",
-                        reason="OSX have borken `get_value`")
+    @pytest.mark.skipif(
+        sys.platform == "darwin", reason="OSX have borken `get_value`"
+    )
     def test_bounded_semaphore(self):
         sem = loky_context.BoundedSemaphore(2)
         self._test_semaphore(sem)
@@ -135,7 +134,6 @@ def test_timeout(self):
 
 
 class TestCondition:
-
     @classmethod
     def _test_notify(cls, cond, sleeping, woken, timeout=None):
         cond.acquire()
@@ -147,8 +145,10 @@ def _test_notify(cls, cond, sleeping, woken, timeout=None):
     def check_invariant(self, cond):
         # this is only supposed to succeed when there are no sleepers
         try:
-            sleepers = (cond._sleeping_count.get_value() -
-                        cond._woken_count.get_value())
+            sleepers = (
+                cond._sleeping_count.get_value()
+                - cond._woken_count.get_value()
+            )
             sleepers == 0
             cond._wait_semaphore.get_value() == 0
         except NotImplementedError:
@@ -159,13 +159,15 @@ def test_notify(self):
         sleeping = loky_context.Semaphore(0)
         woken = loky_context.Semaphore(0)
 
-        p = loky_context.Process(target=self._test_notify,
-                                 args=(cond, sleeping, woken))
+        p = loky_context.Process(
+            target=self._test_notify, args=(cond, sleeping, woken)
+        )
         p.daemon = True
         p.start()
 
-        p = threading.Thread(target=self._test_notify,
-                             args=(cond, sleeping, woken))
+        p = threading.Thread(
+            target=self._test_notify, args=(cond, sleeping, woken)
+        )
         p.daemon = True
         p.start()
 
@@ -206,13 +208,17 @@ def test_notify_all(self):
 
         # start some threads/processes which will timeout
         for _ in range(3):
-            p = loky_context.Process(target=self._test_notify,
-                                     args=(cond, sleeping, woken, TIMEOUT1))
+            p = loky_context.Process(
+                target=self._test_notify,
+                args=(cond, sleeping, woken, TIMEOUT1),
+            )
             p.daemon = True
             p.start()
 
-            t = threading.Thread(target=self._test_notify,
-                                 args=(cond, sleeping, woken, TIMEOUT1))
+            t = threading.Thread(
+                target=self._test_notify,
+                args=(cond, sleeping, woken, TIMEOUT1),
+            )
             t.daemon = True
             t.start()
 
@@ -230,13 +236,15 @@ def test_notify_all(self):
 
         # start some more threads/processes
         for _ in range(3):
-            p = loky_context.Process(target=self._test_notify,
-                                     args=(cond, sleeping, woken))
+            p = loky_context.Process(
+                target=self._test_notify, args=(cond, sleeping, woken)
+            )
             p.daemon = True
             p.start()
 
-            t = threading.Thread(target=self._test_notify,
-                                 args=(cond, sleeping, woken))
+            t = threading.Thread(
+                target=self._test_notify, args=(cond, sleeping, woken)
+            )
             t.daemon = True
             t.start()
 
@@ -294,8 +302,9 @@ def test_waitfor(self):
         except NotImplementedError:
             pytest.skip("`sem_get_value not implemented")
 
-        p = loky_context.Process(target=self._test_waitfor_f,
-                                 args=(cond, state))
+        p = loky_context.Process(
+            target=self._test_waitfor_f, args=(cond, state)
+        )
         p.daemon = True
         p.start()
 
@@ -323,7 +332,7 @@ def _test_wait_result(cls, c, pid):
             os.kill(pid, signal.SIGINT)
 
     def test_wait_result(self):
-        if sys.platform != 'win32':
+        if sys.platform != "win32":
             pid = os.getpid()
         else:
             pid = None
@@ -333,8 +342,9 @@ def test_wait_result(self):
             assert not c.wait(0)
             assert not c.wait(0.1)
 
-            p = loky_context.Process(target=self._test_wait_result,
-                                     args=(c, pid))
+            p = loky_context.Process(
+                target=self._test_wait_result, args=(c, pid)
+            )
             p.start()
 
             assert c.wait(10)
@@ -345,7 +355,6 @@ def test_wait_result(self):
 
 
 class TestEvent:
-
     @classmethod
     def _test_event(cls, event):
         time.sleep(TIMEOUT1)
diff --git a/tests/test_worker_timeout.py b/tests/test_worker_timeout.py
index cfda1e01..740bd171 100644
--- a/tests/test_worker_timeout.py
+++ b/tests/test_worker_timeout.py
@@ -14,6 +14,7 @@
 
 class SlowlyPickling:
     """Simulate slowly pickling object, e.g. large numpy array or dict"""
+
     def __init__(self, delay=1):
         self.delay = delay
 
@@ -23,7 +24,7 @@ def __reduce__(self):
 
 
 class DelayedSimpleQueue(SimpleQueue):
-    def __init__(self, reducers=None, ctx=None, delay=.1):
+    def __init__(self, reducers=None, ctx=None, delay=0.1):
         super().__init__(reducers=reducers, ctx=ctx)
         self.out_queue = SimpleQueue(ctx=ctx)
         self._inner_reader = self._reader
@@ -35,9 +36,13 @@ def __init__(self, reducers=None, ctx=None, delay=.1):
     def _start_thread(self, delay):
         self._thread = threading.Thread(
             target=DelayedSimpleQueue._feed,
-            args=(self._rlock, self._inner_reader, self.out_queue._writer,
-                  delay),
-            name='QueueDeFeederThread'
+            args=(
+                self._rlock,
+                self._inner_reader,
+                self.out_queue._writer,
+                delay,
+            ),
+            name="QueueDeFeederThread",
         )
         self._thread.daemon = True
 
@@ -67,15 +72,17 @@ def _feed(readlock, reader, writer, delay):
 
 class TestTimeoutExecutor:
     def test_worker_timeout_mock(self):
-        timeout = .001
+        timeout = 0.001
         context = get_context()
         executor = ProcessPoolExecutor(
-            max_workers=4, context=context, timeout=timeout)
-        result_queue = DelayedSimpleQueue(ctx=context, delay=.001)
+            max_workers=4, context=context, timeout=timeout
+        )
+        result_queue = DelayedSimpleQueue(ctx=context, delay=0.001)
         executor._result_queue = result_queue
 
-        with pytest.warns(UserWarning,
-                          match='^A worker stopped while some jobs'):
+        with pytest.warns(
+            UserWarning, match="^A worker stopped while some jobs"
+        ):
             for _ in range(5):
                 # Trigger worker spawn for lazy executor implementations
                 for _ in executor.map(id, range(8)):
@@ -91,23 +98,29 @@ def test_worker_timeout_with_slowly_pickling_objects(self, n_tasks=5):
         pickling large arguments, the executor should ensure that there is an
         appropriate amount of workers to move one and not get stalled.
         """
-        with pytest.warns(UserWarning,
-                          match='^A worker stopped while some jobs'):
-            for timeout, delay in [(0.01, 0.02), (0.01, 0.1), (0.1, 0.1),
-                                   (0.001, .1)]:
-                executor = get_reusable_executor(max_workers=2,
-                                                 timeout=timeout)
+        with pytest.warns(
+            UserWarning, match="^A worker stopped while some jobs"
+        ):
+            for timeout, delay in [
+                (0.01, 0.02),
+                (0.01, 0.1),
+                (0.1, 0.1),
+                (0.001, 0.1),
+            ]:
+                executor = get_reusable_executor(
+                    max_workers=2, timeout=timeout
+                )
                 # First make sure the executor is started
                 executor.submit(id, 42).result()
-                results = list(executor.map(
-                    id, [SlowlyPickling(delay)] * n_tasks))
+                results = list(
+                    executor.map(id, [SlowlyPickling(delay)] * n_tasks)
+                )
                 assert len(results) == n_tasks
 
     def test_worker_timeout_shutdown_no_deadlock(self):
-        """Check that worker timeout don't cause deadlock when shutting down.
-        """
+        """Check that worker timeout don't cause deadlock when shutting down."""
         with warnings.catch_warnings(record=True) as record:
-            with get_reusable_executor(max_workers=2, timeout=.001) as e:
+            with get_reusable_executor(max_workers=2, timeout=0.001) as e:
                 # First make sure the executor is started
                 e.submit(id, 42).result()
 
@@ -120,4 +133,4 @@ def test_worker_timeout_shutdown_no_deadlock(self):
         # there are still pending tasks but this should not cause a deadlock.
         for w in record:
             msg = w.message.args[0]
-            assert 'A worker stopped while some jobs' in msg
+            assert "A worker stopped while some jobs" in msg
diff --git a/tests/utils.py b/tests/utils.py
index 7d93bf13..fbd77fa9 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -55,6 +55,7 @@ def captured_output(stream_name):
     """Return a context manager used by captured_stdout/stdin/stderr
     that temporarily replaces the sys stream *stream_name* with a StringIO."""
     import io
+
     orig_stdout = getattr(sys, stream_name)
     s = io.StringIO()
 
@@ -68,9 +69,9 @@ def captured_output(stream_name):
 def captured_stderr():
     """Capture the output of sys.stderr:
 
-       with captured_stderr() as stderr:
-           print("hello", file=sys.stderr)
-       self.assertEqual(stderr.getvalue(), "hello\\n")
+    with captured_stderr() as stderr:
+        print("hello", file=sys.stderr)
+    self.assertEqual(stderr.getvalue(), "hello\\n")
     """
     return captured_output("stderr")
 
@@ -79,8 +80,8 @@ def captured_stderr():
 # Wrapper
 #
 
-class TimingWrapper:
 
+class TimingWrapper:
     def __init__(self, func):
         self.func = func
         self.elapsed = None
@@ -107,14 +108,16 @@ def assert_timing_almost_zero(self):
 # helper functions
 #
 
+
 def id_sleep(x, delay=0):
     """sleep for delay seconds and return its first argument"""
     time.sleep(delay)
     return x
 
 
-def check_subprocess_call(cmd, timeout=1, stdout_regex=None,
-                          stderr_regex=None, env=None):
+def check_subprocess_call(
+    cmd, timeout=1, stdout_regex=None, stderr_regex=None, env=None
+):
     """Runs a command in a subprocess with timeout in seconds.
 
     Also checks returncode is zero, stdout if stdout_regex is set, and
@@ -123,8 +126,9 @@ def check_subprocess_call(cmd, timeout=1, stdout_regex=None,
     if env is not None:
         env = {**os.environ, **env}
 
-    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
-                            stderr=subprocess.PIPE, env=env, text=True)
+    proc = subprocess.Popen(
+        cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, text=True
+    )
 
     def kill_process():
         warnings.warn(f"Timeout running {cmd}")
@@ -137,23 +141,23 @@ def kill_process():
 
         if proc.returncode == -9:
             message = (
-                f'Subprocess timeout after {timeout}s.\nStdout:\n{stdout}\n'
-                f'Stderr:\n{stderr}')
+                f"Subprocess timeout after {timeout}s.\nStdout:\n{stdout}\n"
+                f"Stderr:\n{stderr}"
+            )
             raise TimeoutError(message)
         elif proc.returncode != 0:
             message = (
-                f'Non-zero return code: {proc.returncode}.\nStdout:\n{stdout}'
-                f'\nStderr:\n{stderr}')
+                f"Non-zero return code: {proc.returncode}.\nStdout:\n{stdout}"
+                f"\nStderr:\n{stderr}"
+            )
             raise ValueError(message)
 
-        if (stdout_regex is not None and
-                not re.search(stdout_regex, stdout)):
+        if stdout_regex is not None and not re.search(stdout_regex, stdout):
             raise ValueError(
                 f"Unexpected stdout: {stdout_regex!r} does not match:"
                 f"\n{stdout!r}"
             )
-        if (stderr_regex is not None and
-                not re.search(stderr_regex, stderr)):
+        if stderr_regex is not None and not re.search(stderr_regex, stderr):
             raise ValueError(
                 f"Unexpected stderr: {stderr_regex!r} does not "
                 f"match:\n{stderr!r}"
@@ -168,6 +172,7 @@ def kill_process():
 def skip_func(msg):
     def test_func(*args, **kwargs):
         pytest.skip(msg)
+
     return test_func
 
 
@@ -180,9 +185,10 @@ def with_numpy(func):
         return func
 
 except ImportError:
+
     def with_numpy(func):
         """A decorator to skip tests requiring numpy."""
-        return skip_func('Test require numpy')
+        return skip_func("Test require numpy")
 
 
 # A decorator to run tests only when numpy is available
@@ -197,9 +203,10 @@ def _run_openmp_parallel_sum(*args):
         return parallel_sum(*args)
 
 except ImportError:
+
     def with_parallel_sum(func):
         """A decorator to skip tests if parallel_sum is not compiled."""
-        return skip_func('Test requires parallel_sum to be compiled')
+        return skip_func("Test requires parallel_sum to be compiled")
 
     _run_openmp_parallel_sum = None
 
@@ -209,7 +216,7 @@ def check_python_subprocess_call(code, stdout_regex=None, timeout=10):
     try:
         fid, filename = mkstemp(suffix="_joblib.py")
         os.close(fid)
-        with open(filename, mode='w') as f:
+        with open(filename, mode="w") as f:
             f.write(code)
         cmd += [filename]
         check_subprocess_call(cmd, stdout_regex=stdout_regex, timeout=timeout)