Checking if a variable is a dictionary
gagsl-py2 at yahoo.com.ar
Mon Mar 10 05:45:46 CET 2008
On 9 mar, 11:23, Steven D'Aprano <st... at REMOVE-THIS-
> On Sun, 09 Mar 2008 06:58:15 -0700, Guillermo wrote:
> > Okay, so I think I know where's the catch now -- you must rely on the
> > fact that the protocol is implemented, there's no way to enforce it if
> > you're expecting a parrot-like object. You'd try to call the speak()
> > method and deal with the error if there's no such method?
> That's right. That's called "duck typing" -- if all you want is something
> that quacks like a duck, then it doesn't matter if it actually is a duck
> or not.
In addition to duck typing, in some cases an explicit declaration may
be useful: "I implement the Parrot protocol". The zope.interface
package does that: there is a way to define interfaces (a set of
methods any implementation must provide), and classes can assert "I
implement this interface", and one can determine whether a class
implements or not certain interface. See http://pypi.python.org/pypi/zope.interface
Abstract Base Classes (ABC, for Python 3.0) provide a similar concept
(but they're not the same thing). See http://www.python.org/dev/peps/pep-3119/
Of course there is some overlapping between all of these techniques -
one should choose the best method in each case.
More information about the Python-list