Supplying a function with an annotation about its return type
The special syntax
def funcName() -> type
adds the key
'return'
to the
__annotations__
dictionary. The value for this key is the specified
type:
def sayHello() -> str:
return 'hello world'
print('sayHello() is supposed to return a {}'.format(sayHello.__annotations__['return'].__name__))
#
# sayHello() is supposed to return a str
It should be noted that the annotated type is not enforced at runtime:
def Func() -> int:
return 'haha, not an int'
print(Func())
Supplying annotations about a function parameter
def F(num: 'A number',
txt: 'A text' ='Hello World'):
print('num:', num)
print('txt:', txt)
print('')
F(42)
F(txt = 'good bye', num = 99)
print('Annotations:')
for annot, val in F.__annotations__.items():
print('{:4s}: {}'.format(annot, val))