expect – Primitive Type Expectations

This module implements a more declarative and unified interface for these two scenarios:

if isinstance(foo, SomeType):
    pass ## do something
else:
    pass ## handle exceptional situation
if some_assertion_holds(foo):
    pass ## do something
else:
    pass ## handle exceptional situation

Some have noted that that isinstance() is considered harmful. Using expect() with abc Abstract Base Classes instead of concrete classes will add flexibility to your code.

>>> from md.expect import *

Expectations

expect(obj, interface, cast=None)

Declare the expectation that obj conforms to interface and return obj if it does. If it does not and cast is given, return cast(obj); otherwise raise an UnexpectedType exception. The interface may be a type, tuple of types, or a Callable that must return True or False when interface(obj) is called.

The two required arguments of this operation are intentionally similar to adapt() of PEP-246. This is to make it easy to use as a primitive for type-checking libraries that consume function annotations.

>>> from numbers import Number

>>> expect(1, Number)
1

>>> expect("6F", Number)
...
UnexpectedType: expected Number, not <str '6F'>

>>> expect("6F", Number, lambda hex: int(hex, 16))
111
meets_expectation(obj, interface)

Return True if expect(obj, interface) would succeed, False otherwise. No exception is raised.

>>> meets_expectation(1, Number)
True

>>> meets_expectation("6F", Number)
False
is_expectable(interface)

Return True if interface is a suitable second argument to expect().

>>> is_expectable(basestring)
True

>>> is_expectable('foo')
False

Errors

exception UnexpectedType(value, interface, *args)

This subclass of TypeError is raised when expect() fails. It is guaranteed to have two additional properties defined: value and interface, which were the first two arguments to expect().

>>> try:
...     print expect("6F", Number)
... except UnexpectedType as exc:
...     print 'Caught exception', exc.value, exc.interface
Caught exception 6F <class 'numbers.Number'>

Table Of Contents

Previous topic

abc – Abstract Base Class Enhancements

Next topic

fluid – Fluid Bindings

This Page