Bare forward slash in Python function definition? [duplicate]

耗尽温柔 提交于 2019-12-06 16:29:03

问题


In the Python 3.8 Programming FAQ, I saw the following function definition:

class callByRef:
    def __init__(self, /, **args):
        for key, value in args.items():
            setattr(self, key, value)

This is missing in the Python 3.7 version:

class callByRef:
    def __init__(self, **args):
        for (key, value) in args.items():
            setattr(self, key, value)

What is this new / syntax?

How does it relate to a / appearing in help() output?


Note: this and this question are about help() annotation, whereas this question is about new syntax and any differences to the help() annotation.


回答1:


Introduction as syntax

The / as syntax was introduced in Python 3.8.

The rationale for / in an argument list is given in PEP 570 -- Python Positional-Only Parameters:

The new syntax will enable library authors to further control how their API can be called. It will allow designating which parameters must be called as positional-only, while preventing them from being called as keyword arguments.

Previously, (informational) PEP 457 defined the syntax, but with a much more vague scope. This PEP takes the original proposal a step further by justifying the syntax and providing an implementation for the / syntax in function definitions.

Comparison of syntax and annotational PEPs

Similarities

For all intents and purposes, if you understand help()'s / notation, then that's what is formally included as Python syntax in v3.8 via PEP 570.

Differences

  • PEP 570 -- Python Positional-Only Parameters

    • Defines the syntax of Python 3.8+
    • Formal grammatical specification of the syntax
    • Type: Accepted
  • PEP 457 -- Notation For Positional-Only Parameters

    • Defines notation (not syntax) used in help() annotations
    • Informal English language description
    • Type: Informational

Explanation and example

There are already excellent answers on the meaning and usage of / in arguments.

To save you the click through:

A / means that all preceding parameters are positional-only parameters. Positional-only parameters before a / cannot be passed as name=value when calling the function.

Python 3.8 What's New gives the following example:

def pow(x, y, z=None, /):
    r = x**y
    if z is not None:
        r %= z
    return r

Valid function calls:

  • pow(2, 10)
  • pow(2, 10, 17)

Invalid function calls:

  • pow(x=2, y=10)
  • pow(2, 10, z=17)


来源:https://stackoverflow.com/questions/56514297/bare-forward-slash-in-python-function-definition

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