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
« prev ^ index » next coverage.py v7.13.4, created at 2026-05-08 20:23 +0000
1#!/usr/bin/python
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
8# -*- coding: utf-8 -*-
9from __future__ import annotations
11from functools import wraps
12from typing import TYPE_CHECKING, TypeVar, cast
14from oc_ocdm.abstract_entity import AbstractEntity
16if TYPE_CHECKING:
17 from typing import Callable
18F = TypeVar('F', bound='Callable[..., object]')
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.
27 The expected type can be expressed through a short string:
29 * '_dataset_' for the ``Dataset`` entities;
30 * the OCDM short name in case of any other entity (e.g. 'br' for ``BibliographicResource``).
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()
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__))
47 return cast(F, accepts_only_wrapper)
48 return accepts_only_decorator