Implements class invariants, pre/postconditions in a way similar to PyDBC, but significantly better.
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 | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
###############################################################################
#
# Yet another invariant/pre-/postcondition design-by-contract support module.
#
# Written by Dmitry Dvoinikov <dmitry@targeted.org>
# Distributed under MIT license.
#
# The latest version, complete with self-tests can be downloaded from:
# http://www.targeted.org/python/recipes/ipdbc.py
#
# Sample usage:
#
# import ipdbc.py
#
# class Balloon(ContractBase): # demonstrates class invariant
# def invariant(self):
# return 0 <= self.weight < 1000 # returns True/False
# def __init__(self):
# self.weight = 0
# def fails(self): # upon return this throws PostInvariantViolationError
# self.weight = 1000
#
# class GuidedBalloon(Balloon): # demonstrates pre/post condition
# def pre_drop(self, _weight): # pre_ receives exact copy of arguments
# return self.weight >= _weight # returns True/False
# def drop(self, _weight):
# self.weight -= _weight;
# return self.weight # the result of the call is passed
# def post_drop(self, result, _weight): # as a second parameter to post_
# return result >= 0 # followed again by copy of arguments
#
# Note: GuidedBalloon().fails() still fails, since Balloon's invariant is
# inherited.
# Note: All the dbc infused methods are inherited in the mro-correct way.
# Note: Neither classmethods nor staticmethods are decorated, only "regular"
# instance-bound methods.
#
# (c) 2005, 2006 Dmitry Dvoinikov <dmitry@targeted.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
###############################################################################
__all__ = ["ContractBase", "ContractViolationError", "InvariantViolationError",
"PreInvariantViolationError", "PostInvariantViolationError",
"PreConditionViolationError", "PostConditionViolationError",
"PreconditionViolationError", "PostconditionViolationError" ]
CONTRACT_CHECKS_ENABLED = True # allows to turn contract checks off when needed
###############################################################################
class ContractViolationError(AssertionError): pass
class InvariantViolationError(ContractViolationError): pass
class PreInvariantViolationError(InvariantViolationError): pass
class PostInvariantViolationError(InvariantViolationError): pass
class PreConditionViolationError(ContractViolationError): pass
PreconditionViolationError = PreConditionViolationError # pep 316 calls it such
class PostConditionViolationError(ContractViolationError): pass
PostconditionViolationError = PostConditionViolationError # pep 316 calls it such
###############################################################################
from types import FunctionType
from sys import hexversion
have_python_24 = hexversion >= 0x2040000
################################################################################
def any(s, f = lambda e: bool(e)):
for e in s:
if f(e):
return True
else:
return False
################################################################################
def none(s, f = lambda e: bool(e)):
return not any(s, f)
################################################################################
def empty(s):
return len(s) == 0
################################################################################
def pick_first(s, f = lambda e: bool(e)):
for e in s:
if f(e):
return e
else:
return None
################################################################################
if not have_python_24:
def reversed(s):
r = list(s)
r.reverse()
return r
################################################################################
def merged_mro(*classes):
"""
Returns list of all classes' bases merged and mro-correctly ordered,
implemented as per http://www.python.org/2.3/mro.html
"""
if any(classes, lambda c: not isinstance(c, type)):
raise TypeError("merged_mro expects all it's parameters to be classes, got %s" %
pick_first(classes, lambda c: not isinstance(c, type)))
def merge(lists):
result = []
lists = [ (list_[0], list_[1:]) for list_ in lists ]
while not empty(lists):
good_head, tail = pick_first(lists, lambda ht1: none(lists, lambda ht2: ht1[0] in ht2[1])) or (None, None)
if good_head is None:
raise TypeError("Cannot create a consistent method resolution "
"order (MRO) for bases %s" %
", ".join([ cls.__name__ for cls in classes ]))
result += [ good_head ]
i = 0
while i < len(lists):
head, tail = lists[i]
if head == good_head:
if empty(tail):
del(lists[i])
else:
lists[i] = ( tail[0], tail[1:] )
i += 1
else:
i += 1
return result
merged = [ cls.mro() for cls in classes ] + [ list(classes) ]
return merge(merged)
###############################################################################
class ContractFactory(type):
def _wrap(_method, preinvariant, precondition, postcondition, postinvariant,
_classname, _methodname):
def preinvariant_check(result):
if not result:
raise PreInvariantViolationError(
"Class invariant does not hold before a call to %s.%s"
% (_classname, _methodname))
def precondition_check(result):
if not result:
raise PreConditionViolationError(
"Precondition failed before a call to %s.%s"
% (_classname, _methodname))
def postcondition_check(result):
if not result:
raise PostConditionViolationError(
"Postcondition failed after a call to %s.%s"
% (_classname, _methodname))
def postinvariant_check(result):
if not result:
raise PostInvariantViolationError(
"Class invariant does not hold after a call to %s.%s"
% (_classname, _methodname))
if preinvariant is not None and precondition is not None \
and postcondition is not None and postinvariant is not None:
def dbc_wrapper(self, *args, **kwargs):
preinvariant_check(preinvariant(self))
precondition_check(precondition(self, *args, **kwargs))
result = _method(self, *args, **kwargs)
postcondition_check(postcondition(self, result, *args, **kwargs))
postinvariant_check(postinvariant(self))
return result
elif preinvariant is not None and precondition is not None \
and postcondition is not None and postinvariant is None:
def dbc_wrapper(self, *args, **kwargs):
preinvariant_check(preinvariant(self))
precondition_check(precondition(self, *args, **kwargs))
result = _method(self, *args, **kwargs)
postcondition_check(postcondition(self, result, *args, **kwargs))
return result
elif preinvariant is not None and precondition is not None \
and postcondition is None and postinvariant is not None:
def dbc_wrapper(self, *args, **kwargs):
preinvariant_check(preinvariant(self))
precondition_check(precondition(self, *args, **kwargs))
result = _method(self, *args, **kwargs)
postinvariant_check(postinvariant(self))
return result
elif preinvariant is not None and precondition is not None \
and postcondition is None and postinvariant is None:
def dbc_wrapper(self, *args, **kwargs):
preinvariant_check(preinvariant(self))
precondition_check(precondition(self, *args, **kwargs))
result = _method(self, *args, **kwargs)
return result
elif preinvariant is not None and precondition is None \
and postcondition is not None and postinvariant is not None:
def dbc_wrapper(self, *args, **kwargs):
preinvariant_check(preinvariant(self))
result = _method(self, *args, **kwargs)
postcondition_check(postcondition(self, result, *args, **kwargs))
postinvariant_check(postinvariant(self))
return result
elif preinvariant is not None and precondition is None \
and postcondition is not None and postinvariant is None:
def dbc_wrapper(self, *args, **kwargs):
preinvariant_check(preinvariant(self))
result = _method(self, *args, **kwargs)
postcondition_check(postcondition(self, result, *args, **kwargs))
return result
elif preinvariant is not None and precondition is None \
and postcondition is None and postinvariant is not None:
def dbc_wrapper(self, *args, **kwargs):
preinvariant_check(preinvariant(self))
result = _method(self, *args, **kwargs)
postinvariant_check(postinvariant(self))
return result
elif preinvariant is not None and precondition is None \
and postcondition is None and postinvariant is None:
def dbc_wrapper(self, *args, **kwargs):
preinvariant_check(preinvariant(self))
result = _method(self, *args, **kwargs)
return result
elif preinvariant is None and precondition is not None \
and postcondition is not None and postinvariant is not None:
def dbc_wrapper(self, *args, **kwargs):
precondition_check(precondition(self, *args, **kwargs))
result = _method(self, *args, **kwargs)
postcondition_check(postcondition(self, result, *args, **kwargs))
postinvariant_check(postinvariant(self))
return result
elif preinvariant is None and precondition is not None \
and postcondition is not None and postinvariant is None:
def dbc_wrapper(self, *args, **kwargs):
precondition_check(precondition(self, *args, **kwargs))
result = _method(self, *args, **kwargs)
postcondition_check(postcondition(self, result, *args, **kwargs))
return result
elif preinvariant is None and precondition is not None \
and postcondition is None and postinvariant is not None:
def dbc_wrapper(self, *args, **kwargs):
precondition_check(precondition(self, *args, **kwargs))
result = _method(self, *args, **kwargs)
postinvariant_check(postinvariant(self))
return result
elif preinvariant is None and precondition is not None \
and postcondition is None and postinvariant is None:
def dbc_wrapper(self, *args, **kwargs):
precondition_check(precondition(self, *args, **kwargs))
result = _method(self, *args, **kwargs)
return result
elif preinvariant is None and precondition is None \
and postcondition is not None and postinvariant is not None:
def dbc_wrapper(self, *args, **kwargs):
result = _method(self, *args, **kwargs)
postcondition_check(postcondition(self, result, *args, **kwargs))
postinvariant_check(postinvariant(self))
return result
elif preinvariant is None and precondition is None \
and postcondition is not None and postinvariant is None:
def dbc_wrapper(self, *args, **kwargs):
result = _method(self, *args, **kwargs)
postcondition_check(postcondition(self, result, *args, **kwargs))
return result
elif preinvariant is None and precondition is None \
and postcondition is None and postinvariant is not None:
def dbc_wrapper(self, *args, **kwargs):
result = _method(self, *args, **kwargs)
postinvariant_check(postinvariant(self))
return result
elif preinvariant is None and precondition is None \
and postcondition is None and postinvariant is None:
def dbc_wrapper(self, *args, **kwargs):
result = _method(self, *args, **kwargs)
return result
if have_python_24:
dbc_wrapper.__name__ = _methodname
return dbc_wrapper
_wrap = staticmethod(_wrap)
def __new__(_class, _name, _bases, _dict):
# because the mro for the class being created is not yet available
# we'll have to build it by hand using our own mro implementation
mro = merged_mro(*_bases) # the lack of _class itself in mro is compensated ...
dict_with_bases = {}
for base in reversed(mro):
if hasattr(base, "__dict__"):
dict_with_bases.update(base.__dict__)
dict_with_bases.update(_dict) # ... here by explicitly adding it's method last
try:
invariant = dict_with_bases["invariant"]
except KeyError:
invariant = None
for name, target in dict_with_bases.iteritems():
if isinstance(target, FunctionType) and name != "__del__" and name != "invariant" \
and not name.startswith("pre_") and not name.startswith("post_"):
try:
pre = dict_with_bases["pre_%s" % name]
except KeyError:
pre = None
try:
post = dict_with_bases["post_%s" % name]
except KeyError:
post = None
# note that __del__ is not checked at all
_dict[name] = ContractFactory._wrap(target,
name != "__init__" and invariant or None,
pre or None, post or None, invariant or None,
_name, name)
return super(ContractFactory, _class).__new__(_class, _name, _bases, _dict)
class ContractBase(object):
if CONTRACT_CHECKS_ENABLED:
__metaclass__ = ContractFactory
###############################################################################
|
Why implementing DBC ? Because it's very useful.
Why another implementation ? Let's compare this implementation to PyDBC.
This implementation is better than PyDBC:
- It provides natural inheritance for all the DBC special methods so that the DBC constraints span class hierachies.
- It's DBC methods follow different call convention - they return True/False rather than throwing AssertionError's. The errors are thus reported in a consistent way, rather than forcing the developer to come up with a different message each time. The DBC exceptions being thrown form the hierarchy identical to PEP 316's, rather than ad-hoc.
- Postcondition guarding methods take not just the return value of the method being guarded, but the copy of it's parameters as well (although this is minor).
This implementation is different from PyDBC (better or worse to one's taste):
- To equip a class with DBC you must inherit from ContractBase, rather than set a metaclass (yet it's the same under the hood).
- Method naming is different: invariant, pre_foo and post_foo rather than __invar, foo__pre and foo__post.
- It doesn't decorate __setattr__ as the PyDBC does, so that direct assignments to instance variables could break the class invariant, but this is an intentional decision. For one, DBC is an interface, not syntax feature. For two, with Python anything can be bypassed. For three, __setattr__ could be used in a miriads of ways and it'd be bad if DBC gets in the way.
As to the PEP 316 which offers DBC for Python - I actively refuse to accept it, with it's docstrings code embedding leading to inheritance weirdness, although it appears to be better in that it follows the preweak/poststrengthen rule.
Nice! I like your recipe!