Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/attr/setters.py: 33%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

30 statements  

1# SPDX-License-Identifier: MIT 

2 

3""" 

4Commonly used hooks for on_setattr. 

5""" 

6 

7from . import _config 

8from .exceptions import FrozenAttributeError 

9 

10 

11def pipe(*setters): 

12 """ 

13 Run all *setters* and return the return value of the last one. 

14 

15 .. warning:: 

16 Generators are not allowed in ``pipe()``. 

17 

18 .. versionadded:: 20.1.0 

19 """ 

20 

21 def wrapped_pipe(instance, attrib, new_value): 

22 rv = new_value 

23 

24 for setter in setters: 

25 rv = setter(instance, attrib, rv) 

26 

27 return rv 

28 

29 return wrapped_pipe 

30 

31 

32def frozen(_, __, ___): 

33 """ 

34 Prevent an attribute to be modified. 

35 

36 .. versionadded:: 20.1.0 

37 """ 

38 raise FrozenAttributeError 

39 

40 

41def validate(instance, attrib, new_value): 

42 """ 

43 Run *attrib*'s validator on *new_value* if it has one. 

44 

45 .. versionadded:: 20.1.0 

46 """ 

47 if _config._run_validators is False: 

48 return new_value 

49 

50 v = attrib.validator 

51 if not v: 

52 return new_value 

53 

54 v(instance, attrib, new_value) 

55 

56 return new_value 

57 

58 

59def convert(instance, attrib, new_value): 

60 """ 

61 Run *attrib*'s converter -- if it has one -- on *new_value* and return the 

62 result. 

63 

64 .. versionadded:: 20.1.0 

65 """ 

66 c = attrib.converter 

67 if c: 

68 # This can be removed once we drop 3.8 and use attrs.Converter instead. 

69 from ._make import Converter 

70 

71 if not isinstance(c, Converter): 

72 return c(new_value) 

73 

74 return c(new_value, instance, attrib) 

75 

76 return new_value 

77 

78 

79# Sentinel for disabling class-wide *on_setattr* hooks for certain attributes. 

80# Sphinx's autodata stopped working, so the docstring is inlined in the API 

81# docs. 

82NO_OP = object()