/usr/lib/python2.7/dist-packages/kiwi/python.py is in python-kiwi 1.9.22-4.
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 | #
# Kiwi: a Framework and Enhanced Widgets for Python
#
# Copyright (C) 2005,2006 Async Open Source
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#
# Author(s): Johan Dahlin <jdahlin@async.com.br>
#
"""Generic python addons"""
import sys
import warnings
__all__ = ['ClassInittableMetaType', 'ClassInittableObject']
class ClassInittableMetaType(type):
# pylint fails to understand this is a metaclass
def __init__(self, name, bases, namespace):
type.__init__(self, name, bases, namespace)
self.__class_init__(namespace)
class ClassInittableObject(object):
"""
I am an object which will call a classmethod called
__class_init__ when I am created.
Subclasses of me will also have __class_init__ called.
Note that __class_init__ is called when the class is created,
eg when the file is imported at the first time.
It's called after the class is created, but before it is put
in the namespace of the module where it is defined.
"""
__metaclass__ = ClassInittableMetaType
def __class_init__(cls, namespace):
"""
Called when the class is created
@param cls: class
@param namespace: namespace for newly created
@type namespace: dict
"""
__class_init__ = classmethod(__class_init__)
class _ForwardedProperty(object):
def __init__(self, attribute):
self._attribute = attribute
def __get__(self, instance, klass):
if instance is None:
return self
return getattr(instance.target, self._attribute)
def __set__(self, instance, value):
if instance is None:
raise TypeError
setattr(instance.target, self._attribute, value)
class AttributeForwarder(ClassInittableObject):
"""
AttributeForwarder is an object which is used to forward certain
attributes to another object.
@cvar attributes: list of attributes to be forwarded
@ivar target: forwarded object
"""
attributes = None
def __class_init__(cls, ns):
if cls.__bases__ == (ClassInittableObject,):
return
if not 'attributes' in ns:
raise TypeError(
"the class variable attributes needs to be set for %s" % (
cls.__name__))
if "target" in ns['attributes']:
raise TypeError("'target' is a reserved attribute")
for attribute in ns['attributes']:
setattr(cls, attribute, _ForwardedProperty(attribute))
__class_init__ = classmethod(__class_init__)
def __init__(self, target):
"""
Create a new AttributeForwarder object.
@param target: object to forward attributes to
"""
self.target = target
# copied from twisted/python/reflect.py
def namedAny(name):
"""Get a fully named package, module, module-global object, or attribute.
@param name:
@returns: object, module or attribute
"""
names = name.split('.')
topLevelPackage = None
moduleNames = names[:]
while not topLevelPackage:
try:
trialname = '.'.join(moduleNames)
topLevelPackage = __import__(trialname)
except ImportError:
# if the ImportError happened in the module being imported,
# this is a failure that should be handed to our caller.
# count stack frames to tell the difference.
import traceback
exc_info = sys.exc_info()
if len(traceback.extract_tb(exc_info[2])) > 1:
try:
# Clean up garbage left in sys.modules.
del sys.modules[trialname]
except KeyError:
# Python 2.4 has fixed this. Yay!
pass
raise exc_info[0], exc_info[1], exc_info[2]
moduleNames.pop()
obj = topLevelPackage
for n in names[1:]:
obj = getattr(obj, n)
return obj
class Settable:
"""
A mixin class for syntactic sugar. Lets you assign attributes by
calling with keyword arguments; for example, C{x(a=b,c=d,y=z)} is the
same as C{x.a=b;x.c=d;x.y=z}. The most useful place for this is
where you don't want to name a variable, but you do want to set
some attributes; for example, C{X()(y=z,a=b)}.
"""
def __init__(self, **kw):
self._attrs = kw.keys()
self._attrs.sort()
for k, v in kw.iteritems():
setattr(self, k, v)
def getattributes(self):
"""
Fetches the attributes used to create this object
@returns: a dictionary with attributes
"""
return self._attrs
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__,
', '.join(
['%s=%r' % (attr, getattr(self, attr)) for attr in self._attrs]))
def qual(klass):
"""
Convert a class to a string representation, which is the name of the module
plut a dot plus the name of the class.
@returns: fully qualified module and class name
"""
return klass.__module__ + '.' + klass.__name__
def clamp(x, low, high):
"""
Ensures that x is between the limits set by low and high.
For example,
* clamp(5, 10, 15) is 10.
* clamp(15, 5, 10) is 10.
* clamp(20, 15, 25) is 20.
@param x: the value to clamp.
@param low: the minimum value allowed.
@param high: the maximum value allowed.
@returns: the clamped value
"""
return min(max(x, low), high)
def slicerange(slice, limit):
"""Takes a slice object and returns a range iterator
@param slice: slice object
@param limit: maximum value allowed
@returns: iterator
"""
return xrange(*slice.indices(limit))
_no_deprecation = False
def deprecationwarn(msg, stacklevel=2):
"""
Prints a deprecation warning
"""
global _no_deprecation
if _no_deprecation:
return
warnings.warn(msg, DeprecationWarning, stacklevel=stacklevel)
def disabledeprecationcall(func, *args, **kwargs):
"""
Disables all deprecation warnings during the function call to func
"""
global _no_deprecation
old = _no_deprecation
_no_deprecation = True
retval = func(*args, **kwargs)
_no_deprecation = old
return retval
class enum(int):
"""
enum is an enumered type implementation in python.
To use it, define an enum subclass like this:
>>> from kiwi.python import enum
>>>
>>> class Status(enum):
>>> OPEN, CLOSE = range(2)
>>> Status.OPEN
'<Status value OPEN>'
All the integers defined in the class are assumed to be enums and
values cannot be duplicated
"""
__metaclass__ = ClassInittableMetaType
#@classmethod
def __class_init__(cls, ns):
cls.names = {} # name -> enum
cls.values = {} # value -> enum
for key, value in ns.items():
if isinstance(value, int):
cls(value, key)
__class_init__ = classmethod(__class_init__)
#@classmethod
def get(cls, value):
"""
Lookup an enum by value
@param value: the value
"""
if not value in cls.values:
raise ValueError("There is no enum for value %d" % (value,))
return cls.values[value]
get = classmethod(get)
def __new__(cls, value, name):
"""
Create a new Enum.
@param value: value of the enum
@param name: name of the enum
"""
if name in cls.names:
raise ValueError("There is already an enum called %s" % (name,))
if value in cls.values:
raise ValueError(
"Error while creating enum %s of type %s, "
"it has already been created as %s" % (
value, cls.__name__, cls.values[value]))
self = super(enum, cls).__new__(cls, value)
self.name = name
cls.values[value] = self
cls.names[name] = self
setattr(cls, name, self)
return self
def __str__(self):
return '<%s value %s>' % (
self.__class__.__name__, self.name)
__repr__ = __str__
def all(seq):
"""
Predict used to check if all items in a seq are True.
@returns: True if all items in seq are True
"""
for item in seq:
if not item:
return False
return True
def any(seq):
"""
Predict used to check if any item in a seq are True.
@returns: True if any item in seq is True
"""
for item in seq:
if item:
return True
return False
|