[Python-ideas] Improving the expressivity of function annotations

Paul Moore p.f.moore at gmail.com
Mon Apr 4 12:34:51 CEST 2011


On 4 April 2011 10:56, Masklinn <masklinn at masklinn.net> wrote:
> Yes in that the signature of the methods would be part of the type, no in that the "link" should be implicit (structural)
> not explicit (nominative).
>
> Your example does not show anything as it would be a function annotation (not a type annotation), but making it write
> to a file-like object would work: what I'd like is something along those lines (ignore the notation for now)
>
> class Foo:
>    def write_to(stream: < write(bytes) -> None >):
>        # stuff
>
> class StringWriter:
>    def write(output: str) -> None
>        # stuff
> class BytesWriter:
>    def write(output: bytes) -> None
>        # stuff
>
> d = DuckWriter()
> d.write_to(StringWriter()) -> TypeError, not a structural subtype of what write_to needs
> d.write_to(BytesWriter()) -> OK

I'm not at all sure I follow your intent or terminology (structural vs
nominative) here - perhaps you could provide a full (but short!)
example of what you're trying to do. The above is close, but names
like "Foo" and hiding actual implementations behind "# stuff" is
confusing me.

If I follow what you're after, surely the #stuff in StringWriter would
naturally raise a TypeError when you tried to use a bytes object as if
it were a string? That's essentially what duck typing is about. If
you're trying to enforce stricter typing (closer to the call site, the
nearest Python can get to "compile time" type checking) then why are
you trying to avoid ABCs? Isn't that what they are for?

If what you are after is not (in some sense) a Pythonic version of
static type checking, then I apologise for misunderstanding, but could
you clarify?

Paul.



More information about the Python-ideas mailing list