[Python-ideas] Discussion: Duck typing with “concepts”

James Lu jamtlu at gmail.com
Mon Jan 21 11:15:33 EST 2019

So here’s an interesting idea, not a proposal yet. 

In C++20, a Concept is a list of Boolean expressions with a name that can be used in place of a type in a templated (ie type-generic) function.

from typing import Concept
Iterator = Concept(lambda o: hasattr(o, "__iter__", lambda o: iter(o) != NotImplemented)
# Concept inheritance
Iterable = Concept(lambda o: hasattr(o, "__next__"), Iterator)

You could use concepts to define many practical “real-world” duck types.

A concept is like an opt-in duck typing type assertion. Since it’s a part of type annotation syntax, assertions can be generated automatically by looking at assertions.

You would use a Concept like any other type in type annotations.

Marko, how do you think Concepts might integrate with icontract? (I’m imagining overriding an import hook to automatically add contracts to functions with concepts.) How frequently do you use duck typing at Parquery? How might Concepts affect how often you used duck typing?

More information about the Python-ideas mailing list