2

I was looking at the python 3.3 grammar, and noticed this line in it:

funcdef: 'def' NAME parameters ['->' test] ':' suite

Which means that -> is a valid symbol when defining functions, but I can't find anywhere online that says what it is, and as far as I can tell, it is ignored. For example, I could write code that does this:

def a() -> True: pass

or

def a() -> 5 == 3:
    return 8

are both valid statements but don't seem to do anything.

Can anyone tell me the -> syntax does in python?

poke
  • 369,085
  • 72
  • 557
  • 602
Leif Andersen
  • 21,580
  • 20
  • 67
  • 100
  • Do two people with reopen votes think this _isn't_ a duplicate? Seems like a clear case to me. If there's some distinction the five of us missed, please _edit the question_, or at least comment, to make it explicit. – jscs Feb 25 '13 at 01:16
  • Na, I agree that it's a duplicate (I googled it and couldn't find an answer before I asked). But I really like the answer here, perhaps if we could merge the two questions that would be awesome. – Leif Andersen Feb 25 '13 at 05:42
  • A moderator can do that if you flag and request it. – jscs Feb 25 '13 at 05:43
  • Well I added my (edited) answer to the other question, but I cannot delete this answer because it was accepted. Either a moderator needs to do that or you need to delete your question... – dawg Feb 25 '13 at 17:50

1 Answers1

0

These are function annotations covered in PEP 3107. Specifically, the -> marks the return function annotation.

Examples:

>>> def kinetic_energy(m:'in KG', v:'in M/S')->'Joules': 
...    return 1/2*m*v**2
... 
>>> kinetic_energy.__annotations__
{'return': 'Joules', 'v': 'in M/S', 'm': 'in KG'}

Annotations are dictionaries, so you can do this:

>>> '{:,} {}'.format(kenetic_energy(20,3000),
      kenetic_energy.__annotations__['return'])
'90,000,000.0 Joules'

Or, you can use function attributes to validate called values:

def validate(func, locals):
    for var, test in func.__annotations__.items():
        value = locals[var]
        try: 
            pr=test.__name__+': '+test.__docstring__
        except AttributeError:
            pr=test.__name__   
        msg = '{}=={}; Test: {}'.format(var, value, pr)
        assert test(value), msg

def between(lo, hi):
    def _between(x):
            return lo <= x <= hi
    _between.__docstring__='must be between {} and {}'.format(lo,hi)       
    return _between

def f(x: between(3,10), y:lambda _y: isinstance(_y,int)):
    validate(f, locals())
    print(x,y)

Prints

>>> f(2,2) 
AssertionError: x==2; Test: _between: must be between 3 and 10
>>> f(3,2.1)
AssertionError: y==2.1; Test: <lambda>
dawg
  • 98,345
  • 23
  • 131
  • 206