playground: python safeint type

safeint.py source


safeint type is supposed to help  simplifying the logic of computations with integers explicitly defined within some boundaries when you want the results of safeint algebraic operations to also respect the defined boundaries.



this is just part of a bigger playground related to a system of runtime constraints that one may declare for user-defined types. ofcourse, python not being a statically-typed language, the notion of "safe types" is a little bit overrated here but "almost safe types" would be a paranoid module name.

currently, operations between different safeint types are allowed. the boundaries constraint will be applied following the rules defined for the left operand (that is, safeint1 + safeint2 will be checked against safeint1 defined constraints)



using safeints:

safeint_factory is a class type factory. the first parameter is the typename, the rest are key/value pairs specifying a minimum, a maximum and a default value (latter is optional). It will inject the type's class definition into the current caller's frame globals.

>>> from safeint import safeint_factory

>>> safeint_factory('IPV4_BYTE',vmin=0,vmax=255)
>>> IPV4_BYTE
<class 'safeint.IPV4_BYTE'>
>>> map(lambda ipbyte: IPV4_BYTE(int(ipbyte)), '1.2.3.4'.split('.'))
[1, 2, 3, 4]
>>> map(lambda ipbyte: IPV4_BYTE(int(ipbyte)), '1.258.3.4'.split('.'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
  File "safeint.py", line 60, in __new__
    raise OverflowError
OverflowError
>>>

>>> safeint_factory('ttl',vmin=0,vmax=2147483647,vdef=14400)
>>> xttl=ttl()
>>> xttl
14400
>>> xttl+=14
>>> xttl
14414
>>> xttl-=2147483647
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "safeint.py", line 20, in f_op
    return safeint.__new__(self.__class__,getattr(super(safeint,self),'__' + op + '__')(other))
  File "safeint.py", line 52, in __new__
    raise OverflowError
OverflowError
>>>

the module is on sysami google project hosting




No comments:

Post a Comment