What does -> mean in Python function definitions?

后端 未结 8 1527
我寻月下人不归
我寻月下人不归 2020-11-22 07:29

I\'ve recently noticed something interesting when looking at Python 3.3 grammar specification:

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


        
相关标签:
8条回答
  • 2020-11-22 08:09

    It's a function annotation.

    In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values.

    There's no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring.

    0 讨论(0)
  • 2020-11-22 08:10

    This means the type of result the function returns, but it can be None.

    It is widespread in modern libraries oriented on Python 3.x.

    For example, it there is in code of library pandas-profiling in many places for example:

    def get_description(self) -> dict:
    
    def get_rejected_variables(self, threshold: float = 0.9) -> list:
    
    def to_file(self, output_file: Path or str, silent: bool = True) -> None:
    """Write the report to a file.
    
    0 讨论(0)
提交回复
热议问题