/usr/share/pyshared/kiwi/argcheck.py is in python-kiwi 1.9.22-2.
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 | #
# 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>
#
"""
Argument checking decorator and support
"""
import inspect
from types import ClassType
from kiwi.datatypes import number as number_type
class CustomType(type):
def value_check(mcs, name, value):
pass
value_check = classmethod(value_check)
class number(CustomType):
"""
Custom type that verifies that the type is a number (eg float or int)
"""
type = number_type
class percent(CustomType):
"""
Custom type that verifies that the value is a percentage
"""
type = number_type
def value_check(mcs, name, value):
if (value < 0) or (value > 100):
raise ValueError("%s must be between 0 and 100" % name)
value_check = classmethod(value_check)
_NoValue = object()
class argcheck(object):
"""
Decorator to check type and value of arguments.
Usage:
>>> @argcheck(types...)
... def function(args..)
or
>>> class Class:
... @argcheck(types..)
... def method(self, args)
You can customize the checks by subclassing your type from CustomType,
there are two builtin types: number which is a float/int combined check
and a percent which verifis that the value is a percentage
"""
__enabled__ = True
def __init__(self, *types):
for argtype in types:
if not isinstance(argtype, (type, ClassType)):
raise TypeError("must be a type or class instance, not %r" % argtype)
self.types = types
def enable(cls):
"""
Enable argcheck globally
"""
cls.__enabled__ = True
enable = classmethod(enable)
def disable(cls):
"""
Disable argcheck globally
"""
cls.__enabled__ = False
disable = classmethod(disable)
def __call__(self, func):
if not callable(func):
raise TypeError("%r must be callable" % func)
# Useful for optimized runs
if not self.__enabled__:
return func
spec = inspect.getargspec(func)
arg_names, is_varargs, is_kwargs, default_values = spec
if not default_values:
default_values = []
else:
default_values = list(default_values)
# Set all the remaining default values to _NoValue
default_values = ([_NoValue] * (len(arg_names) - len(default_values)) +
default_values)
# TODO: Is there another way of doing this?
# Not trivial since func is not attached to the class at
# this point. Nor is the class attached to the namespace.
if arg_names and arg_names[0] in ('self', 'cls'):
arg_names = arg_names[1:]
default_values = default_values[1:]
is_method = True
else:
is_method = False
types = self.types
if is_kwargs and not is_varargs and self.types:
raise TypeError("argcheck cannot be used with only keywords")
elif not is_varargs:
if len(types) != len(arg_names):
raise TypeError("%s has wrong number of arguments, "
"%d specified in decorator, "
"but function has %d" %
(func.__name__,
len(types),
len(arg_names)))
kwarg_types = {}
kwarg_defaults = {}
for i, arg_name in enumerate(arg_names):
kwarg_types[arg_name] = types[i]
value = default_values[i]
kwarg_defaults[arg_name] = value
if value is None or value is _NoValue:
continue
arg_type = types[i]
try:
self._type_check(value, arg_type, arg_name)
except TypeError:
raise TypeError("default value for %s must be of type %s "
"and not %s" % (arg_name,
arg_type.__name__,
type(value).__name__))
kwarg_defaults[arg_name] = value
def wrapper(*args, **kwargs):
if self.__enabled__:
cargs = args
if is_method:
cargs = cargs[1:]
# Positional arguments
for arg, type, name, default in zip(cargs, types, arg_names,
default_values):
self._type_check(arg, type, name, default)
# Keyword arguments
for name, arg in kwargs.items():
if not name in kwarg_types:
raise TypeError(
"%s() got an unexpected keyword argument '%s'"
% (func.__name__, name))
self._type_check(arg, kwarg_types[name], name,
kwarg_defaults[name])
self.extra_check(arg_names, types, args, kwargs)
return func(*args, **kwargs)
# Python 2.3 does not support assignments to __name__
try:
wrapper.__name__ = func.__name__
except TypeError:
pass
return wrapper
def extra_check(self, names, types, args, kwargs):
pass
def _type_check(self, value, argument_type, name, default=_NoValue):
if default is not _NoValue and value == default:
return
if issubclass(argument_type, CustomType):
custom = True
check_type = argument_type.type
else:
custom = False
check_type = argument_type
type_name = argument_type.__name__
if not isinstance(value, check_type):
raise TypeError(
"%s must be %s, not %s" % (name, type_name,
type(value).__name__))
if custom:
argument_type.value_check(name, value)
|