Function Annotations giving error in python?

流过昼夜 提交于 2020-01-15 04:51:33

问题


So I made a function, and wanted to add annotations to it, and the compiler keeps giving me an error:

def square_root(x:number, eps:number) -> float:
    pass

And the compiler returns this:

  File "/Users/albertcalzaretto/Google Drive/CSC148H1/e1/e1a.py", line 1
    def square_root(x, eps) -> float:
                            ^
SyntaxError: invalid syntax

I've never used function annotations, and I've read several sources about it, and I don't think what I'm doing is wrong.


回答1:


Two things:

  1. You must be using Python 2.x somehow. Function annotations are only supported in Python 3.x. If you try to use them in Python 2.x, you will get a SyntaxError:

    >>> def f() -> int:
      File "<stdin>", line 1
        def f() -> int:
                ^
    SyntaxError: invalid syntax
    >>>
    
  2. If number is undefined (which I believe it is), then you need to make it a string so that you don't get a NameError. Below is a demonstration:

    >>> def square_root(x:number, eps:number) -> float:
    ...     pass
    ...
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'number' is not defined
    >>>
    >>> def square_root(x:'number', eps:'number') -> float:
    ...     pass
    ...
    >>>
    


来源:https://stackoverflow.com/questions/21170521/function-annotations-giving-error-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!