monkeypatch to fix perf problems from nptyping

This commit is contained in:
sneakers-the-rat 2023-09-06 19:32:33 -07:00
parent 6a9d612b41
commit 7b97b749ef
3 changed files with 48 additions and 1 deletions

View file

@ -1 +1,5 @@
from nwb_linkml.maps import preload
from nwb_linkml.monkeypatch import apply_patches
apply_patches()
from nwb_linkml.maps import preload

View file

@ -0,0 +1,43 @@
"""
Monkeypatches to external modules
"""
def patch_npytyping():
"""
npytyping makes an expensive call to inspect.stack()
that makes imports of pydantic models take ~200x longer than
they should:
References:
- https://github.com/ramonhagenaars/nptyping/issues/110
"""
from nptyping import ndarray
from nptyping.pandas_ import dataframe
from nptyping import recarray
from nptyping import base_meta_classes
import inspect
from types import FrameType
# make a new __module__ methods for the affected classes
def new_module_ndarray(cls) -> str:
return cls._get_module(inspect.currentframe(), 'nptyping.ndarray')
def new_module_recarray(cls) -> str:
return cls._get_module(inspect.currentframe(), 'nptyping.recarray')
def new_module_dataframe(cls) -> str:
return cls._get_module(inspect.currentframe(), 'nptyping.pandas_.dataframe')
# and a new _get_module method for the parent class
def new_get_module(cls, stack: FrameType, module: str) -> str:
return "typing" if inspect.getframeinfo(stack.f_back).function == "formatannotation" else module
# now apply the patches
ndarray.NDArrayMeta.__module__ = property(new_module_ndarray)
recarray.RecArrayMeta.__module__ = property(new_module_recarray)
dataframe.DataFrameMeta.__module__ = property(new_module_dataframe)
base_meta_classes.SubscriptableMeta._get_module = new_get_module
def apply_patches():
patch_npytyping()