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

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

29 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 .. versionadded:: 20.1.0 

16 """ 

17 

18 def wrapped_pipe(instance, attrib, new_value): 

19 rv = new_value 

20 

21 for setter in setters: 

22 rv = setter(instance, attrib, rv) 

23 

24 return rv 

25 

26 return wrapped_pipe 

27 

28 

29def frozen(_, __, ___): 

30 """ 

31 Prevent an attribute to be modified. 

32 

33 .. versionadded:: 20.1.0 

34 """ 

35 raise FrozenAttributeError() 

36 

37 

38def validate(instance, attrib, new_value): 

39 """ 

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

41 

42 .. versionadded:: 20.1.0 

43 """ 

44 if _config._run_validators is False: 

45 return new_value 

46 

47 v = attrib.validator 

48 if not v: 

49 return new_value 

50 

51 v(instance, attrib, new_value) 

52 

53 return new_value 

54 

55 

56def convert(instance, attrib, new_value): 

57 """ 

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

59 result. 

60 

61 .. versionadded:: 20.1.0 

62 """ 

63 c = attrib.converter 

64 if c: 

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

66 from ._make import Converter 

67 

68 if not isinstance(c, Converter): 

69 return c(new_value) 

70 

71 return c(new_value, instance, attrib) 

72 

73 return new_value 

74 

75 

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

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

78# docs. 

79NO_OP = object()