Duck checker in Python: does one exist?

Posted by elliot42 on Programmers See other posts from Programmers or by elliot42
Published on 2012-03-30T21:23:24Z Indexed on 2012/04/10 11:41 UTC
Read the original article Hit count: 408

Filed under:
|

Python uses duck-typing, rather than static type checking. But many of the same concerns ultimately apply: does an object have the desired methods and attributes? Do those attributes have valid, in-range values?

Whether you're writing constraints in code, or writing test cases, or validating user input, or just debugging, inevitably somewhere you'll need to verify that an object is still in a proper state--that it still "looks like a duck" and "quacks like a duck."

In statically typed languages you can simply declare "int x", and anytime you create or mutate x, it will always be a valid int. It seems feasible to decorate a Python object to ensure that it is valid under certain constraints, and that every time that object is mutated it is still valid under those constraints. Ideally there would be a simple declarative syntax to express "hasattr length and length is non-negative" (not in those words. Not unlike Rails validators, but less human-language and more programming-language). You could think of this as ad-hoc interface/type system, or you could think of it as an ever-present object-level unit test.

Does such a library exist to declare and validate constraint/duck-checking on Python-objects? Is this an unreasonable tool to want? :)

(Thanks!)


Contrived example:

rectangle = {'length': 5, 'width': 10}

# We live in a fictional universe where multiplication is super expensive.  
# Therefore any time we multiply, we need to cache the results.

def area(rect):
    if 'area' in rect:
        return rect['area']
    rect['area'] = rect['length'] * rect['width']
    return rect['area']

print area(rectangle)
rectangle['length'] = 15
print area(rectangle) # compare expected vs. actual output!

# imagine the same thing with object attributes rather than dictionary keys.

© Programmers or respective owner

Related posts about python

Related posts about type-system