/usr/lib/python2.7/dist-packages/tables/misc/enum.py is in python-tables 3.1.1-3.
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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | # -*- coding: utf-8 -*-
########################################################################
#
# License: BSD
# Created: May 4, 2005
# Author: Ivan Vilata i Balaguer - reverse:net.selidor@ivan
#
# $Id$
#
########################################################################
"""Implementation of enumerated types.
This module provides the `Enum` class, which can be used to construct
enumerated types. Those types are defined by providing an *exhaustive
set or list* of possible, named values for a variable of that type.
Enumerated variables of the same type are usually compared between them
for equality and sometimes for order, but are not usually operated upon.
Enumerated values have an associated *name* and *concrete value*. Every
name is unique and so are concrete values. An enumerated variable
always takes the concrete value, not its name. Usually, the concrete
value is not used directly, and frequently it is entirely irrelevant.
For the same reason, an enumerated variable is not usually compared with
concrete values out of its enumerated type. For that kind of use,
standard variables and constants are more adequate.
"""
from tables._past import previous_api
__docformat__ = 'reStructuredText'
"""The format of documentation strings in this module."""
class Enum(object):
"""Enumerated type.
Each instance of this class represents an enumerated type. The
values of the type must be declared
*exhaustively* and named with
*strings*, and they might be given explicit
concrete values, though this is not compulsory. Once the type is
defined, it can not be modified.
There are three ways of defining an enumerated type. Each one
of them corresponds to the type of the only argument in the
constructor of Enum:
- *Sequence of names*: each enumerated
value is named using a string, and its order is determined by
its position in the sequence; the concrete value is assigned
automatically::
>>> boolEnum = Enum(['True', 'False'])
- *Mapping of names*: each enumerated
value is named by a string and given an explicit concrete value.
All of the concrete values must be different, or a
ValueError will be raised::
>>> priority = Enum({'red': 20, 'orange': 10, 'green': 0})
>>> colors = Enum({'red': 1, 'blue': 1})
Traceback (most recent call last):
...
ValueError: enumerated values contain duplicate concrete values: 1
- *Enumerated type*: in that case, a copy
of the original enumerated type is created. Both enumerated
types are considered equal::
>>> prio2 = Enum(priority)
>>> priority == prio2
True
Please note that names starting with _ are
not allowed, since they are reserved for internal usage::
>>> prio2 = Enum(['_xx'])
Traceback (most recent call last):
...
ValueError: name of enumerated value can not start with ``_``: '_xx'
The concrete value of an enumerated value is obtained by
getting its name as an attribute of the Enum
instance (see __getattr__()) or as an item (see
__getitem__()). This allows comparisons between
enumerated values and assigning them to ordinary Python
variables::
>>> redv = priority.red
>>> redv == priority['red']
True
>>> redv > priority.green
True
>>> priority.red == priority.orange
False
The name of the enumerated value corresponding to a concrete
value can also be obtained by using the
__call__() method of the enumerated type. In this
way you get the symbolic name to use it later with
__getitem__()::
>>> priority(redv)
'red'
>>> priority.red == priority[priority(priority.red)]
True
(If you ask, the __getitem__() method is
not used for this purpose to avoid ambiguity in the case of using
strings as concrete values.)
"""
def __init__(self, enum):
mydict = self.__dict__
mydict['_names'] = {}
mydict['_values'] = {}
if isinstance(enum, list) or isinstance(enum, tuple):
for (value, name) in enumerate(enum): # values become 0, 1, 2...
self._check_and_set_pair(name, value)
elif isinstance(enum, dict):
for (name, value) in enum.iteritems():
self._check_and_set_pair(name, value)
elif isinstance(enum, Enum):
for (name, value) in enum._names.iteritems():
self._check_and_set_pair(name, value)
else:
raise TypeError("""\
enumerations can only be created from \
sequences, mappings and other enumerations""")
def _check_and_set_pair(self, name, value):
"""Check validity of enumerated value and insert it into type."""
names = self._names
values = self._values
if not isinstance(name, basestring):
raise TypeError(
"name of enumerated value is not a string: %r" % (name,))
if name.startswith('_'):
raise ValueError(
"name of enumerated value can not start with ``_``: %r"
% name)
# This check is only necessary with a sequence base object.
if name in names:
raise ValueError(
"enumerated values contain duplicate names: %r" % name)
# This check is only necessary with a mapping base object.
if value in values:
raise ValueError(
"enumerated values contain duplicate concrete values: %r"
% value)
names[name] = value
values[value] = name
self.__dict__[name] = value
_checkAndSetPair = previous_api(_check_and_set_pair)
def __getitem__(self, name):
"""Get the concrete value of the enumerated value with that name.
The name of the enumerated value must be a string. If there is no value
with that name in the enumeration, a KeyError is raised.
Examples
--------
Let ``enum`` be an enumerated type defined as:
>>> enum = Enum({'T0': 0, 'T1': 2, 'T2': 5})
then:
>>> enum['T1']
2
>>> enum['foo']
Traceback (most recent call last):
...
KeyError: "no enumerated value with that name: 'foo'"
"""
try:
return self._names[name]
except KeyError:
raise KeyError("no enumerated value with that name: %r" % (name,))
def __setitem__(self, name, value):
"""This operation is forbidden."""
raise IndexError("operation not allowed")
def __delitem__(self, name):
"""This operation is forbidden."""
raise IndexError("operation not allowed")
def __getattr__(self, name):
"""Get the concrete value of the enumerated value with that name.
The name of the enumerated value must be a string. If there is no value
with that name in the enumeration, an AttributeError is raised.
Examples
--------
Let ``enum`` be an enumerated type defined as:
>>> enum = Enum({'T0': 0, 'T1': 2, 'T2': 5})
then:
>>> enum.T1
2
>>> enum.foo
Traceback (most recent call last):
...
AttributeError: no enumerated value with that name: 'foo'
"""
try:
return self[name]
except KeyError as ke:
raise AttributeError(*ke.args)
def __setattr__(self, name, value):
"""This operation is forbidden."""
raise AttributeError("operation not allowed")
def __delattr__(self, name):
"""This operation is forbidden."""
raise AttributeError("operation not allowed")
def __contains__(self, name):
"""Is there an enumerated value with that name in the type?
If the enumerated type has an enumerated value with that name, True is
returned. Otherwise, False is returned. The name must be a string.
This method does *not* check for concrete values matching a value in an
enumerated type. For that, please use the :meth:`Enum.__call__` method.
Examples
--------
Let ``enum`` be an enumerated type defined as:
>>> enum = Enum({'T0': 0, 'T1': 2, 'T2': 5})
then:
>>> 'T1' in enum
True
>>> 'foo' in enum
False
>>> 0 in enum
Traceback (most recent call last):
...
TypeError: name of enumerated value is not a string: 0
>>> enum.T1 in enum # Be careful with this!
Traceback (most recent call last):
...
TypeError: name of enumerated value is not a string: 2
"""
if not isinstance(name, basestring):
raise TypeError(
"name of enumerated value is not a string: %r" % (name,))
return name in self._names
def __call__(self, value, *default):
"""Get the name of the enumerated value with that concrete value.
If there is no value with that concrete value in the enumeration and a
second argument is given as a default, this is returned. Else, a
ValueError is raised.
This method can be used for checking that a concrete value belongs to
the set of concrete values in an enumerated type.
Examples
--------
Let ``enum`` be an enumerated type defined as:
>>> enum = Enum({'T0': 0, 'T1': 2, 'T2': 5})
then:
>>> enum(5)
'T2'
>>> enum(42, None) is None
True
>>> enum(42)
Traceback (most recent call last):
...
ValueError: no enumerated value with that concrete value: 42
"""
try:
return self._values[value]
except KeyError:
if len(default) > 0:
return default[0]
raise ValueError(
"no enumerated value with that concrete value: %r" % (value,))
def __len__(self):
"""Return the number of enumerated values in the enumerated type.
Examples
--------
>>> len(Enum(['e%d' % i for i in range(10)]))
10
"""
return len(self._names)
def __iter__(self):
"""Iterate over the enumerated values.
Enumerated values are returned as (name, value) pairs *in no particular
order*.
Examples
--------
>>> enumvals = {'red': 4, 'green': 2, 'blue': 1}
>>> enum = Enum(enumvals)
>>> enumdict = dict([(name, value) for (name, value) in enum])
>>> enumvals == enumdict
True
"""
for name_value in self._names.iteritems():
yield name_value
def __eq__(self, other):
"""Is the other enumerated type equivalent to this one?
Two enumerated types are equivalent if they have exactly the same
enumerated values (i.e. with the same names and concrete values).
Examples
--------
Let ``enum*`` be enumerated types defined as:
>>> enum1 = Enum({'T0': 0, 'T1': 2})
>>> enum2 = Enum(enum1)
>>> enum3 = Enum({'T1': 2, 'T0': 0})
>>> enum4 = Enum({'T0': 0, 'T1': 2, 'T2': 5})
>>> enum5 = Enum({'T0': 0})
>>> enum6 = Enum({'T0': 10, 'T1': 20})
then:
>>> enum1 == enum1
True
>>> enum1 == enum2 == enum3
True
>>> enum1 == enum4
False
>>> enum5 == enum1
False
>>> enum1 == enum6
False
Comparing enumerated types with other kinds of objects produces
a false result:
>>> enum1 == {'T0': 0, 'T1': 2}
False
>>> enum1 == ['T0', 'T1']
False
>>> enum1 == 2
False
"""
if not isinstance(other, Enum):
return False
return self._names == other._names
def __ne__(self, other):
"""Is the `other` enumerated type different from this one?
Two enumerated types are different if they don't have exactly
the same enumerated values (i.e. with the same names and
concrete values).
Examples
--------
Let ``enum*`` be enumerated types defined as:
>>> enum1 = Enum({'T0': 0, 'T1': 2})
>>> enum2 = Enum(enum1)
>>> enum3 = Enum({'T1': 2, 'T0': 0})
>>> enum4 = Enum({'T0': 0, 'T1': 2, 'T2': 5})
>>> enum5 = Enum({'T0': 0})
>>> enum6 = Enum({'T0': 10, 'T1': 20})
then:
>>> enum1 != enum1
False
>>> enum1 != enum2 != enum3
False
>>> enum1 != enum4
True
>>> enum5 != enum1
True
>>> enum1 != enum6
True
"""
return not self.__eq__(other)
# XXX: API incompatible change for PyTables 3 line
# Overriding __eq__ blocks inheritance of __hash__ in 3.x
# def __hash__(self):
# return hash((self.__class__, tuple(self._names.items())))
def __repr__(self):
"""Return the canonical string representation of the enumeration. The
output of this method can be evaluated to give a new enumeration object
that will compare equal to this one.
Examples
--------
>>> repr(Enum({'name': 10}))
"Enum({'name': 10})"
"""
return 'Enum(%s)' % self._names
def _test():
import doctest
return doctest.testmod()
if __name__ == '__main__':
_test()
## Local Variables:
## mode: python
## py-indent-offset: 4
## tab-width: 4
## fill-column: 72
## End:
|