Coverage for oc_ocdm / decorators.py: 93%

15 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-05-08 20:23 +0000

1#!/usr/bin/python 

2 

3# SPDX-FileCopyrightText: 2020-2022 Simone Persiani <iosonopersia@gmail.com> 

4# SPDX-FileCopyrightText: 2024-2026 Arcangelo Massari <arcangelo.massari@unibo.it> 

5# 

6# SPDX-License-Identifier: ISC 

7 

8# -*- coding: utf-8 -*- 

9from __future__ import annotations 

10 

11from functools import wraps 

12from typing import TYPE_CHECKING, TypeVar, cast 

13 

14from oc_ocdm.abstract_entity import AbstractEntity 

15 

16if TYPE_CHECKING: 

17 from typing import Callable 

18F = TypeVar('F', bound='Callable[..., object]') 

19 

20 

21def accepts_only(param_type: str) -> Callable[[F], F]: 

22 """ 

23 A decorator that can be applied to the entity methods such as setters and removers 

24 when they accept a parameter. It enforces the right parameter type by raising a 

25 ``TypeError`` when the parameter is not None but its type is not the expected one. 

26 

27 The expected type can be expressed through a short string: 

28 

29 * '_dataset_' for the ``Dataset`` entities; 

30 * the OCDM short name in case of any other entity (e.g. 'br' for ``BibliographicResource``). 

31 

32 :param param_type: A short string representing the expected type 

33 :type param_type: str 

34 """ 

35 def accepts_only_decorator(function: F) -> F: 

36 lowercase_type = param_type.lower() 

37 

38 @wraps(function) 

39 def accepts_only_wrapper(self: object, param: object = None, **kwargs: object) -> object: 

40 if param is None or \ 

41 (isinstance(param, AbstractEntity) and param.short_name == lowercase_type): 

42 return function(self, param, **kwargs) 

43 else: 

44 raise TypeError('[%s.%s] Expected argument type: %s. Provided argument type: %s.' % 

45 (self.__class__.__name__, function.__name__, lowercase_type, type(param).__name__)) 

46 

47 return cast(F, accepts_only_wrapper) 

48 return accepts_only_decorator