/usr/lib/python3/dist-packages/plainbox/impl/symbol.py is in python3-plainbox 0.25-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | # This file is part of Checkbox.
#
# Copyright 2013 Canonical Ltd.
# Written by:
# Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
#
# Checkbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3,
# as published by the Free Software Foundation.
#
# Checkbox is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Checkbox. If not, see <http://www.gnu.org/licenses/>.
"""
:mod:`plainbox.impl.symbol` -- Symbol Type
==========================================
Symbols are special values that evaluate back to themselves. They are global,
unlike enumeration values, and are not bound to any container that defined
them. Symbols can be easily converted to strings and back and are a useful way
to store constants for use inside applications or libraries.
Applications can use Symbol class directly or use the SymbolDef helper to
quickly construct symbols without syntax overhead.
"""
__all__ = ['Symbol', 'SymbolDef']
import functools
import inspect
@functools.total_ordering
class Symbol:
"""
Symbol type.
Instances of this class behave as self-interning strings. All instances are
tracked and at most one instance with a given symbol name can be
constructed. The name is immutable.
"""
__symbols = {}
def __new__(cls, name):
"""
Create a new symbol instance.
If the name was already used in another symbol then that object is
returned directly. If the name was not used before then construct a new
Symbol instance and return it.
"""
try:
return cls.__symbols[name]
except KeyError:
symbol = object.__new__(cls)
cls.__symbols[name] = symbol
return symbol
def __init__(self, name):
"""
Initialize a symbol with the given name
"""
self._name = name
@property
def name(self):
"""
name of the symbol
"""
return self._name
def __str__(self):
"""
Convert the symbol object to its name
"""
return self._name
def __repr__(self):
"""
Convert the symbol object to its representation in python
"""
return "{}({!r})".format(self.__class__.__name__, self._name)
def __eq__(self, other):
"""
Compare two symbols or a string and a symbol for equality
"""
if isinstance(other, Symbol):
return self is other
elif isinstance(other, str):
return self._name == other
else:
return NotImplemented
def __lt__(self, other):
"""
Compare two symbols or a string and a symbol for inequality
"""
if isinstance(other, Symbol):
return self._name < other._name
elif isinstance(other, str):
return self._name < other
else:
return NotImplemented
def __hash__(self):
"""
Has the name of the symbol
"""
return hash(self._name)
class SymbolDefNs:
"""
Internal implementation detail of the symbol module.
A special namespace used by :class:`SymbolDefMeta` to keep track of names
that were being accessed. Each accessed name is converted to a
:class:`Symbol` and added to the namespace.
"""
PASSTHRU = frozenset(('__name__', '__qualname__', '__doc__', '__module__'))
def __init__(self, allow_outer=None):
self.data = {}
self.allow_outer = allow_outer
def __setitem__(self, name, value):
if name in self.PASSTHRU:
self.data[name] = value
elif isinstance(value, Symbol):
self.data[name] = value
elif isinstance(value, str):
self.data[name] = Symbol(value)
else:
raise ValueError("Only Symbol() instances can be assigned here")
def __getitem__(self, name):
if name in self.PASSTHRU:
return self.data[name]
elif self.allow_outer is not None and name in self.allow_outer:
raise KeyError(name)
elif name in self.data:
return self.data[name]
elif name == 'Symbol':
return Symbol
else:
symbol = Symbol(name)
self.data[name] = symbol
return symbol
class SymbolDefMeta(type):
"""
Metaclass for :class:`SymbolDef` which helps to construct multiple symbol
objects easily. Uses :class:`SymbolDefNs` to keep track of all the symbol
definitions inside the class and convert them to a list of candidate
symbols to define.
"""
@classmethod
def __prepare__(mcls, name, bases, allow_outer=None, **kwargs):
return SymbolDefNs(allow_outer)
def __new__(mcls, name, bases, ns, allow_outer=None):
classdict = ns.data
classdict['get_all_symbols'] = classmethod(mcls.get_all_symbols)
return type.__new__(mcls, name, bases, classdict)
def __init__(mcls, name, bases, ns, allow_outer=None):
super().__init__(name, bases, ns)
# This is inserted via a simple trick because it's very hard to do any
# normal method definition inside SymbolDef blocks.
@staticmethod
def get_all_symbols(cls):
"""
Get all symbols defined by this symbol definition block
"""
# NOTE: This feels a bit like Enum and the extra property that it
# carries which holds all values. I don't know if we should have that
# as symbols are not 'bound' to any 'container' like enumeration values
# are.
return [value for name, kind, defcls, value
in inspect.classify_class_attrs(cls)
if name != '__locals__' and kind == 'data'
and isinstance(value, Symbol)]
class SymbolDef(metaclass=SymbolDefMeta):
"""
Helper class that allows to easily define symbols.
All sub-classes of SymbolDef are evaluated specially. Each word used inside
the class definition becomes a Symbol() instance. In addition explicit
assignment can create new symbols. This can be used to create symbols with
value different from their identifiers.
"""
|