[Python-ideas] Improving the expressivity of function annotations
Carl M. Johnson
cmjohnson.mailinglist at gmail.com
Mon Apr 4 10:44:43 CEST 2011
On Sun, Apr 3, 2011 at 10:31 PM, Masklinn <masklinn at masklinn.net> wrote:
> Structural types
> ================
>
> The third issue is also the biggest by far. A small portion of it is resolved by abcs (especially if tools include special support for ABCs), but not all of it by a long shot: statically defining and checking "duck types". abcs check for structure, so they are a convenient label for *some* "duck" types but their meaning isn't even well defined (e.g. does the ``item: Mapping`` signature mean ``item`` implements the abstract methods of Mapping, or does it have to *also* implement the mixin methods, even if Mapping was not actually mixed in it?)
>
> Anyway this is where "structural types" come in: defining a type not by its name but by its shape (a set of methods and properties, and their signatures).
>
> Again, this can be handled by defining (enough) abcs, but it soon becomes tiresome as ABCs are still pretty verbose to write and I don't doubt there would soon be about 5 million versions of ``Readable`` (requirement of a single no-args method ``read`` producing bytes). As a result, the ability to define a type as a set of methods (and their signatures) without having to give it an explicit name would — I think — be great.
It wouldn't be that hard to make a class decorator that would work like:
@interface
class Duck:
def quack(): pass
def walk(): pass
class Mallard:
def quack():
print("quack")
def walk():
print("waddle")
assert issubclass(Mallard, Duck) #Passes.
Where "interface" is a loose term like Go, and anything with the
relevant methods counts as a subclass. It would probably make sense to
add something like that to the abc module.
More information about the Python-ideas
mailing list