Skip to content

Commit

Permalink
Handle all possible ImportErrors for lazy modules
Browse files Browse the repository at this point in the history
  • Loading branch information
aatle committed Dec 1, 2024
1 parent 711c5e0 commit 2aeeee0
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions src_py/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,9 +306,11 @@ def PixelArray(surface): # pylint: disable=unused-argument


def lazy_import(name):
"""See https://docs.python.org/3/library/importlib.html#implementing-lazy-imports
"""Lazily import a pygame module.
See https://docs.python.org/3/library/importlib.html#implementing-lazy-imports
Only load the module upon its first attribute access.
Only load modules upon their first attribute access.
Lazily imported modules are directly referenced in packager_imports function.
"""
spec = find_spec("pygame." + name)
Expand All @@ -320,15 +322,22 @@ def lazy_import(name):
return module


if find_spec("numpy") is not None:
numpy_exists = find_spec("numpy") is not None

# Preserve MissingModule behavior when numpy is not installed
# and when their pygame module dependencies are unavailable

if numpy_exists and not isinstance(pixelcopy, MissingModule):
surfarray = lazy_import("surfarray")
sndarray = lazy_import("sndarray")
else:
# Preserve MissingModule behavior when numpy is not installed
surfarray = MissingModule("surfarray", urgent=0)

if numpy_exists and not isinstance(mixer, MissingModule):
sndarray = lazy_import("sndarray")
else:
sndarray = MissingModule("sndarray", urgent=0)

del LazyLoader, find_spec, lazy_import, module_from_spec
del LazyLoader, find_spec, lazy_import, module_from_spec, numpy_exists

try:
import pygame._debug
Expand Down

0 comments on commit 2aeeee0

Please sign in to comment.