Coverage for local_installation_linux/mumott/core/deprecation_warning.py: 94%

30 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2024-08-11 23:08 +0000

1import warnings 

2import functools 

3from inspect import isfunction, isclass 

4from typing import Union 

5 

6 

7def print_deprecation_warning(warning_message: str, stack_level: int = 3): 

8 warnings.simplefilter('always', DeprecationWarning) # turn off filter 

9 warnings.warn(warning_message, 

10 category=DeprecationWarning, 

11 stacklevel=3) 

12 warnings.simplefilter('default', DeprecationWarning) # reset filter 

13 

14 

15def deprecated(extra_message: str = ''): 

16 """This is a decorator which can be used to mark classes 

17 and functions as deprecated. It will result in a warning being emitted 

18 when the function is used. 

19 

20 Parameters 

21 ---------- 

22 dep_obj 

23 The object (a class or function) to be deprecated. 

24 extra_message 

25 A string that will be printed after the standard deprecation warning, 

26 used to, e.g., suggest usage of a different object. Default is an empty string. 

27 """ 

28 def deprecated_inner(dep_obj: Union[type, callable]): 

29 return_class = False 

30 if isclass(dep_obj): 

31 obj_name = 'Class' 

32 return_class = True 

33 elif isfunction(dep_obj): 33 ↛ 36line 33 didn't jump to line 36, because the condition on line 33 was never false

34 obj_name = 'Function/Method' 

35 else: 

36 raise TypeError(f'Unknown object type {type(dep_obj)}!') 

37 

38 if not return_class: 

39 @functools.wraps(dep_obj) 

40 def new_obj(*args, **kwargs): 

41 print_deprecation_warning(f'{obj_name} {dep_obj.__name__} is deprecated and will be ' 

42 f'removed with the next major version' + extra_message) 

43 return dep_obj(*args, **kwargs) 

44 return new_obj 

45 else: 

46 orig_init = dep_obj.__init__ 

47 

48 def __init__(self, *args, **kwargs): 

49 print_deprecation_warning(f'{obj_name} {dep_obj.__name__} is deprecated and will be ' 

50 f'removed with the next major version' + extra_message) 

51 orig_init(self, *args, **kwargs) 

52 dep_obj.__init__ = __init__ 

53 return dep_obj 

54 return deprecated_inner