File: sentinel.py

package info (click to toggle)
python-collections-extended 2.0.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 492 kB
  • sloc: python: 2,917; makefile: 59
file content (44 lines) | stat: -rw-r--r-- 853 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""Sentinel class."""

__all__ = ('Sentinel', 'NOT_SET')


class Sentinel:
	"""A class to create sentinel objects.

	The benefits vs. object() are a good repr it is picklable.

	Inspired by https://pypi.org/project/sentinels/
	"""

	_registry = {}

	def __getnewargs__(self):
		return self._name,

	def __new__(cls, _name):
		"""Find the Sentinel object with name or create a new one."""
		try:
			return cls._registry[_name]
		except KeyError:
			new = super(Sentinel, cls).__new__(cls)
			cls._registry[_name] = new
			return new

	def __init__(self, name):
		super(Sentinel, self).__init__()
		self._name = name

	def __repr__(self):
		return '<%s>' % self._name

	def __bool__(self):
		return False

	def __eq__(self, other):
		if other.__class__ == self.__class__:
			return self._name == other._name
		return False


NOT_SET = Sentinel('not_set')