0

Is there a way in Python to annotate what interface an argument should satisfy? IE, if you expect a container supporting push and pop and empty as the first argument, to annotate this?

Carbon
  • 3,828
  • 3
  • 24
  • 51
  • 2
    [Might be worth a read](https://stackoverflow.com/questions/8059649/how-to-document-a-duck-type) – Cory Kramer Jun 16 '17 at 18:58
  • Are you asking if there are docstring conventions? Those are defined in [PEP 257](https://www.python.org/dev/peps/pep-0257/) – Mike Scotty Jun 16 '17 at 18:59
  • @CoryKramer I've worked on things in python in the past where an interface is partially filled and then you get garbage, I'm wondering if type annotations or something like them allows safety here. Coming from a functional world, expecting the programmer to the type system in his head seems unreasonable. – Carbon Jun 16 '17 at 19:02

1 Answers1

1

Functions in Python can have signatures, that is what you should look at. In Python3 this is part of the language:

def greeting(name: str) -> str:
    return 'Hello, {}'.format(name)

In python2 you can use # type: (str) -> str.

Apart from built-ins, your own types (with restrictions) can be used for this annotations.

I use this and the mypy package, to check my ruamel.yaml library, slowly increasing the usefulness by replacing Any declarations (which don't restrict at all, hence any) with more restrictive types.

Anthon
  • 69,918
  • 32
  • 186
  • 246