Skip to content

Commit

Permalink
Cache __getitem__ of BaseCollectionModelMeta
Browse files Browse the repository at this point in the history
  • Loading branch information
romis2012 committed Nov 13, 2021
1 parent 81f82b5 commit 33cc7e8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pydantic_collections/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
__title__ = 'pydantic-collections'
__version__ = '0.1.1'
__version__ = '0.2.0'

from ._base_collection_model import BaseCollectionModel

Expand Down
19 changes: 19 additions & 0 deletions pydantic_collections/_base_collection_model.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import functools
import warnings
from typing import Optional, List, MutableSequence, Type, TypeVar, Any, Callable

Expand All @@ -14,7 +15,25 @@ class CollectionModelConfig(BaseConfig):
validate_assignment_strict = False


def tp_cache(func):
"""Internal wrapper caching __getitem__ of generic types with a fallback to
original function for non-hashable arguments.
"""
cached = functools.lru_cache(maxsize=None, typed=True)(func)

@functools.wraps(func)
def inner(*args, **kwargs):
try:
return cached(*args, **kwargs)
except TypeError: # pragma: no cover
pass # All real errors (not unhashable args) are raised below.
return func(*args, **kwargs) # pragma: no cover

return inner


class BaseCollectionModelMeta(ModelMetaclass):
@tp_cache
def __getitem__(cls: Type['BaseCollectionModel'], el_type):
if not issubclass(cls, BaseCollectionModel):
raise TypeError('{!r} is not a BaseCollectionModel'.format(cls)) # pragma: no cover
Expand Down

0 comments on commit 33cc7e8

Please sign in to comment.