Debian Codegraph @

lib/ansible/module_utils/common/sentinel.py

raw
1 # Copyright (c) 2019 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import annotations
5
6
7 class Sentinel:
8 """
9 Object which can be used to mark whether an entry as being special
10
11 A sentinel value demarcates a value or marks an entry as having a special meaning. In C, the
12 Null byte is used as a sentinel for the end of a string. In Python, None is often used as
13 a Sentinel in optional parameters to mean that the parameter was not set by the user.
14
15 You should use None as a Sentinel value any Python code where None is not a valid entry. If
16 None is a valid entry, though, then you need to create a different value, which is the purpose
17 of this class.
18
19 Example of using Sentinel as a default parameter value::
20
21 def confirm_big_red_button(tristate=Sentinel):
22 if tristate is Sentinel:
23 print('You must explicitly press the big red button to blow up the base')
24 elif tristate is True:
25 print('Countdown to destruction activated')
26 elif tristate is False:
27 print('Countdown stopped')
28 elif tristate is None:
29 print('Waiting for more input')
30
31 Example of using Sentinel to tell whether a dict which has a default value has been changed::
32
33 values = {'one': Sentinel, 'two': Sentinel}
34 defaults = {'one': 1, 'two': 2}
35
36 # [.. Other code which does things including setting a new value for 'one' ..]
37 values['one'] = None
38 # [..]
39
40 print('You made changes to:')
41 for key, value in values.items():
42 if value is Sentinel:
43 continue
44 print('%s: %s' % (key, value)
45 """
46
47 def __new__(cls):
48 """
49 Return the cls itself. This makes both equality and identity True for comparing the class
50 to an instance of the class, preventing common usage errors.
51
52 Preferred usage::
53
54 a = Sentinel
55 if a is Sentinel:
56 print('Sentinel value')
57
58 However, these are True as well, eliminating common usage errors::
59
60 if Sentinel is Sentinel():
61 print('Sentinel value')
62
63 if Sentinel == Sentinel():
64 print('Sentinel value')
65 """
66 return cls