Skip to content

Commit f235432

Browse files
committed
Rewrite import checks to rely on try-except
1 parent 2aeeee0 commit f235432

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

src_py/__init__.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -322,22 +322,30 @@ def lazy_import(name):
322322
return module
323323

324324

325-
numpy_exists = find_spec("numpy") is not None
325+
# Check if numpy is available for surfarray and sndarray modules
326+
numpy_missing = find_spec("numpy") is None
326327

327-
# Preserve MissingModule behavior when numpy is not installed
328-
# and when their pygame module dependencies are unavailable
329-
330-
if numpy_exists and not isinstance(pixelcopy, MissingModule):
331-
surfarray = lazy_import("surfarray")
332-
else:
328+
try:
329+
if numpy_missing:
330+
# Always fails here. Need the error message for MissingModule.reason
331+
import numpy
332+
# Check that module dependencies are not missing, or get error message
333+
import pygame.pixelcopy
334+
except (ImportError, OSError):
333335
surfarray = MissingModule("surfarray", urgent=0)
334-
335-
if numpy_exists and not isinstance(mixer, MissingModule):
336-
sndarray = lazy_import("sndarray")
337336
else:
337+
surfarray = lazy_import("surfarray")
338+
339+
try:
340+
if numpy_missing:
341+
import numpy
342+
import pygame.mixer
343+
except (ImportError, OSError):
338344
sndarray = MissingModule("sndarray", urgent=0)
345+
else:
346+
sndarray = lazy_import("sndarray")
339347

340-
del LazyLoader, find_spec, lazy_import, module_from_spec, numpy_exists
348+
del LazyLoader, find_spec, lazy_import, module_from_spec, numpy_missing
341349

342350
try:
343351
import pygame._debug

0 commit comments

Comments
 (0)