duck-type-checking?

Paul McGuire ptmcg at austin.rr.com
Sat Nov 15 09:21:04 EST 2008


On Nov 15, 2:50 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> I wonder whether the best solution is to include all your type checks
> (isinstance or duck-typing) in the unit tests, so you can avoid paying
> the cost of those tests at runtime? If your code passes the unit tests,
> but fails with real data, then your unit tests aren't extensive enough.
>
> --
> Steven

The real penalties that you pay for static typing are not at compile
time, but at design time.  Because of duck-typing, Python programmers
can skip a lot of the extra hoops/cruft that Java and C++ developers
must jump through, usually to *get around* the restrictions of static
typing.  Imagine how much code is needed in those languages to
implement this simple generic Proxy class:

class Proxy(object):
    def __init__(self,other):
        self.obj = other
    def __getattr__(self,attr):
        print "Get attribute '%s'" % attr
        return getattr(self.obj,attr)

x = "slfj"
xproxy = Proxy(x)

print xproxy.upper()

# prints:
# Get attribute 'upper'
# SLFJ

I used very similar code to write a CORBA interceptor for a client in
about 15 minutes, which would have taken *much* longer in C++ or Java.

-- Paul



More information about the Python-list mailing list