Merge pull request #7641 from hugovk/optimise-imagemode

Optimise `ImageMode.getmode` using `functools.lru_cache`
This commit is contained in:
Andrew Murray 2023-12-27 09:42:26 +11:00 committed by GitHub
commit 1e8bad805e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -15,9 +15,7 @@
from __future__ import annotations
import sys
# mode descriptor cache
_modes = None
from functools import lru_cache
class ModeDescriptor:
@ -41,14 +39,13 @@ class ModeDescriptor:
return self.mode
@lru_cache
def getmode(mode: str) -> ModeDescriptor:
"""Gets a mode descriptor for the given mode."""
global _modes
if not _modes:
# initialize mode cache
modes = {}
endian = "<" if sys.byteorder == "little" else ">"
for m, (basemode, basetype, bands, typestr) in {
modes = {
# core modes
# Bits need to be extended to bytes
"1": ("L", "L", ("1",), "|b1"),
@ -72,10 +69,12 @@ def getmode(mode: str) -> ModeDescriptor:
"LA": ("L", "L", ("L", "A"), "|u1"),
"La": ("L", "L", ("L", "a"), "|u1"),
"PA": ("RGB", "L", ("P", "A"), "|u1"),
}.items():
modes[m] = ModeDescriptor(m, bands, basemode, basetype, typestr)
# mapping modes
for i16mode, typestr in {
}
if mode in modes:
base_mode, base_type, bands, type_str = modes[mode]
return ModeDescriptor(mode, bands, base_mode, base_type, type_str)
mapping_modes = {
# I;16 == I;16L, and I;32 == I;32L
"I;16": "<u2",
"I;16S": "<i2",
@ -91,8 +90,7 @@ def getmode(mode: str) -> ModeDescriptor:
"I;32S": "<i4",
"I;32BS": ">i4",
"I;32LS": "<i4",
}.items():
modes[i16mode] = ModeDescriptor(i16mode, ("I",), "L", "L", typestr)
# set global mode cache atomically
_modes = modes
return _modes[mode]
}
type_str = mapping_modes[mode]
return ModeDescriptor(mode, ("I",), "L", "L", type_str)