On Thu, Jun 6, 2013 at 7:29 PM, Steven D'Aprano
<steve+comp.lang.pyt...@pearwood.info> wrote:
> Whatever benefit there is in declaring the type of a function is lost due
> to the inability to duck-type or program to an interface. There's no type
> that says "any object with a 'next' method", for example. And having to
> declare local variables is a PITA with little benefit.
>
> Give me a language with type inference, and a nice, easy way to keep duck-
> typing, and I'll reconsider. But until then, I don't believe the benefit
> of static types comes even close to paying for the extra effort.

Here are some classic ways to do the multiple-types-accepted option.

//C++ style: overloading
int max(int a,int b) {return a>b ? a : b;}
float max(float a,float b) {return a>b ? a : b;}
//C++ also lets you go for templates, but leave that aside

//Pike style: piped types
int|float max(int|float a,int|float b) {return a>b ? a : b;}
//This lets you write one lot of code but doesn't let
//you declare that both args must be the same type

# Python style: accept anything, then (maybe) check
def max(a,b): return a if a>b else b
//Pike does this too:
mixed max(mixed a,mixed b) {return a>b ? a : b;}
/* So does C, but only with pointers: */
void *max(void *a,void *b) {... uhh, this is nontrivial actually ...}

For the "accept any object that has a next() method" sorts of rules, I
don't know of any really viable system that does that usefully. The
concept of implementing interfaces in Java comes close, but the class
author has to declare that it's implementing some named interface. In
theory there could be something that deduces the validity from the
given structure, but I'm not aware of any language that does this. But
it would let you do stuff like this (prototyped in Python):

class Integers:
    def __init__(self): self.value=0
    def next(self):
        self.value+=1
        return self.value

interface Iterable:
    next(self)

def grab_three_values(Iterable iter):
    return iter.next(),iter.next(),iter.next()

With a language that checks these sorts of things at compile time,
it's not a big deal to test. With something fully dynamic like Python,
it's probably not worth the effort. But maybe checks like this could
be useful to something like Coverity.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to