Get the App
SLTechnology News&Howtos  ›  Development  › 

PEP570 new syntax: an example analysis of accepting only position parameters

Shulou Source: shulou.com Published: 2022-06-03 18:31:42 10月02日 Update

This article will explain in detail about the new syntax of PEP570: the example analysis that only accepts position parameters, the editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Recently, PEP 570 has been accepted. In fact, the Positional-Only Parameters to be added is used in many of the built-in C functions:

In: _ _ builtin__.evalOut: In: _ _ builtin__.lenOut: In: _ _ builtin__.divmodOut:

If you look at their signatures, they all have a /, / these parameters whose purpose is on the / left, and can only be position parameters (not keyword parameters):

In: divmod (3,2) Out: (1,1) In: divmod (xylene 3, yellow2)-TypeError Traceback (most recent call last) in-> 1 divmod Yellow2) TypeError: divmod () takes no keyword arguments

If you use the keyword argument, an error will be reported. Of course, this mistake is a little baffling. Why do you want to do Positional-Only? Is to force the user to use location parameters!

Look at another example (bytes):

In [68]: bytes??Init signature: bytes (self, /, * args, * * kwargs) Docstring:bytes (iterable_of_ints)-> bytesbytes (string, encoding [, errors])-> bytesbytes (bytes_or_buffer)-> immutable copy of bytes_or_bufferbytes (int)-> bytes object of size given by the parameter initialized with null bytesbytes ()-> empty bytes object...In: bytes ('') 'utf-8') Out: B'\ xe5\ x93\ x88\ xe5\ x93\ x88'In: bytes ('', encoding='utf-8') Out: B'\ xe5\ x93\ x88\ xe5\ x93\ x88'

Although bytes also has /, it only constrains the parameter on the left (there is only one self here), and the subsequent encoding can use either positional parameters or keyword parameters.

With PEP 570, the Python code we wrote can also be supported. You can write like this:

Def name (p1, p2, /, p_or_kw, *, kw): def name (p1, p2=None, /, p_or_kw=None, *, kw): def name (p1, p2=None, /, kw): def name (p1, p2=None, /): def name (p1, p2, /, p_or_kw): def name (p1, p2, /):

We will be able to use this new syntax in Python 3.8. Now you can feel its usage and look forward to it through a few simple examples in PEP.

This is the end of this article on "PEP570 New Grammar: sample Analysis that only accepts location parameters". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Parameters location syntax keywords keywords articles examples analysis examples more good practical inexplicable code users content functions only can pass that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info MariaDB Apple Linux NVidia