This post originated from an RSS feed registered with Python Buzz
by Ian Bicking.
Original Post: Interfaces: Signatures and Semantics
Feed Title: Ian Bicking
Feed URL: http://www.ianbicking.org/feeds/atom.xml
Feed Description: Thoughts on Python and Programming.
Thinking a little about latent interfaces (and latent typing, but
mostly the interfaces) -- one of the issues with an interface in
Python (or this Smalltalk implementation that someone noted in a
comment) is that they consist of method signatures, but nothing about
semantics. This is even more true with latent interfaces (where
latent interfaces are the interfaces you can infer from how code uses
an object).
The way to make latent interfaces safer in a dynamic environment is
generally to choose good method names -- you shouldn't use the same
method name for two conceptually different operations. The example
in the comments to Bruce's post is a method shoot() that may refer to
a Gun or Camera, where each has very different semantic meaning.
A more practical example might be obj.write(value) which might
mean write value to obj (i.e., a file-like object), or write obj to
value (i.e., serialize obj). That's a bad choice of method names,
because they mean very different things, but if you accidentally get
an object that uses the latter semantics where the first are expected,
you could get very weird behavior.
An explicit interface usually implies specific semantics -- that's why
it's okay to have two interfaces which programmatically look the same,
i.e., define the same set of method names and signatures. Usually an
interface also includes documentation which provides a description of
the semantics.
Unfortunately, this doesn't offer any program-accessible semantics,
only programmer-accessible. We can programmatically check signatures,
but how can we check semantics? Statically typed languages are a
little better on this, because their signatures include type
information which starts to define semantic relationships.
Anyway, we still have something more general than static typing in
contracts -- or more concretely, pre- and post-conditions (typically a
bunch of asserts). After all, what's a type declaration besides an
assertion of type? (Well, asserted at compile-time instead of
runtime, but eh)
A neat extension to an interface system (like PyProtocols) would be
to add contracts. The contracts would be attached to the interfaces
themselves, not the particular implementation of those interfaces.
To do this you'd have to change the adapt() function to return a
wrapper -- this wrapper would intercept calls that had interface
contracts, and confirm the contract as well as delegating to the
original code. (There might be other ways -- PEP 246 describes the
lower-level mechanics of adaptation)