Movatterモバイル変換


[0]ホーム

URL:


Following system colour schemeSelected dark colour schemeSelected light colour scheme

Python Enhancement Proposals

PEP 736 – Shorthand syntax for keyword arguments at invocation

Author:
Joshua Bambrick <jbambrick at google.com>,Chris Angelico <rosuav at gmail.com>
Discussions-To:
Discourse thread
Status:
Rejected
Type:
Standards Track
Created:
28-Nov-2023
Python-Version:
3.14
Post-History:
14-Oct-2023,17-Jan-2024,17-Jul-2024
Resolution:
13-Mar-2025

Table of Contents

Abstract

This PEP proposes to introduce syntactic sugarf(x=) for the common patternwhere a keyword argument has the same name as that of the variable correspondingto its valuef(x=x).

Motivation

Keyword argument syntax can become needlessly repetitive and verbose.

Consider the following call:

my_function(my_first_variable=my_first_variable,my_second_variable=my_second_variable,my_third_variable=my_third_variable,)

The case of a keyword argument name matching the variable name of its value isprevalent among Python libraries. This redundancy discourages use of namedarguments and reduces readability by increasing visual noise.

Rationale

There are two ways to invoke a function with arguments: by position and bykeyword. By being explicit, keyword arguments increase readability andminimise the risk of inadvertent transposition. On the flipside, positionalarguments are often preferred simply to minimise verbosity and visual noise.

We contend that a simple syntactic sugar used to simplify this common patternwould confer numerous benefits:

Encourages use of named arguments

By reducing the visual noise that established keyword argument syntax can cause,this syntax would encourage the use of named arguments, thereby increasingreadability and reducing bugs from argument transposition.

Reduces verbosity

By minimising visual noise and in some cases lines of code, we can increasereadability.

Encourages consistent variable names

A common problem is that semantically identical variables have different namesdepending on their contexts. This syntax would encourage authors to use the samevariable name when calling a function as the argument name, which would increaseconsistency of variable names used and hence improve readability.

Highlights arguments not following this pattern

With the current syntax, function calls where many arguments are forwarded fromthe local context can make other argument values easy to miss due to the visualnoise. For example:

add_middleware(excluded_urls=excluded_urls,server_request=server_request,client_request=client_request,client_response=client_response,span_details=_get_span_details(),tracer=tracer,meter=meter,)

With this syntax, the exceptional arguments become easier to identify:

add_middleware(excluded_urls=,server_request=,client_request=,client_response=,span_details=_get_span_details(),tracer=,meter=,)

Applicability to dictionary construction

This syntax can be applied to dictionary construction where a similar patternfrequently occurs (where dictionary keys are identical the names of thevariables assigned as their values),{"x":x,"y":y} ordict(x=x,y=y).With this feature, this can now also be trivially written asdict(x=,y=).Whether to further support similar syntax in dictionary literals is an openquestion beyond the scope of this PEP.

Specification

We propose to introduce syntactic sugar such that, if the value of a keywordargument is omitted from a function invocation, the argument’s value is inferredto be the variable matching that name at the invocation scope.

For example, the function invocation:

my_function(my_first_variable=,my_second_variable=,my_third_variable=)

Will be interpreted exactly equivalently to following in existing syntax:

my_function(my_first_variable=my_first_variable,my_second_variable=my_second_variable,my_third_variable=my_third_variable,)

If no variable matches that name in the invocation scope, aNameError israised in an identical manner as would be with the established expanded syntax.

This proposal only pertains to function invocations; function definitions areunaffected by the syntax change. All existing valid syntax is unchanged.

Backwards Compatibility

Only new syntax is added which was previously syntactically erroneous. Noexisting valid syntax is modified. As such, the changes proposed are fullybackwards compatible.

Security Implications

There are no security implications for this change.

Prior Art

Python already possesses a very similar feature in f-string interpolation wheref'{x=}' is effectively expanded tof'x={x}' (seerelated GitHub issue).

Several modern languages provide similar features during function invocation,sometimes referred to as ‘punning’. For example:

Beyond function invocation specifically, more languages offer similar features:

Applicability

We analysed popular Python libraries from the last few years usingthis scriptto compute:

  • The number of keyword arguments which were of the formf(x=x) atinvocation.
  • The percentage of keyword arguments which had the formf(x=x) atinvocation.
  • The number of lines of code which could be saved by using this syntactic sugarto reduce the need for line wraps.

The purpose of this exercise was to compute statistics about the prevalence ofthis pattern and should not be interpreted as a recommendation that the proposedsyntactic sugar should be applied universally.

StatisticPolarsFastAPIRichHTTPX
Number of keyword arguments of the formf(x=x) at invocation1,6541,408566759
Percentage of keyword arguments of the formf(x=x) at invocation15.83%28.11%15.74%45.13%
Lines saved1703562117

Based on this, we note that thef(x=x) keyword argument pattern iswidespread, accounting for anywhere from 15% to just below half of all keywordargument uses depending on the codebase.

Proposed Syntax

While this feature has been proposed on numerous occasions with severaldifferent forms[1][2][3][4][5],[6] we have opted to advocatefor thef(x=) form for the following reasons:

  • This feature has been proposed frequently over a ten year period with thef(x=) orf(=x) being by far the most commonly suggested syntax[1][2][6]. This strongly indicates that it is the most obvious notation.
  • The proposed syntax closely matches the f-string debugf'{var=}' syntax(established Pythonic style) and serves an almost identical purpose.
  • The proposed syntax is exactly analogous to the Ruby keyword argumentsyntactic sugar. See theRuby 3.1.0 release notes (search for “keyword arguments”).
  • The syntax is easy to implement as it is simple syntactic sugar.
  • When compared to the prefix form (seeRejected Ideas), this syntaxcommunicates “here is a parameter, go find its argument” which is moreappropriate given the semantics of named arguments.
  • A poll of Python developersindicates that this is the most popular syntax among those proposed.

How to Teach This

To ease the communication of and search for this feature, it may also bevaluable to provide this feature with a name, such as ‘keyword argumentshorthand’.

Keen Python developers will likely hear about this feature through typicalinformation channels, such as newsboards, social media, mailing lists, onlineforums, or word of mouth. Many more will encounter this feature while readingcode and noting the omission of the value in a keyword argument at invocation,violating their expectations. We should ensure such developers have easy accessto documentation that explains the semantics of this feature and that thisdocumentation is easy to find when searching. For example, thePython Glossary andTutorialmay be updated accordingly and reasonable keywords may be used to help withsearch discoverability.A StackOverflow questioncould be written to help explain this feature to those searching for anexplanation.

A teacher may explain this feature to new Python programmers as, “where you seean argument followed only by an equals sign, such asf(x=), this representsa keyword argument where the name of the argument and its value are the same.This can be written equivalently in the expanded notation,f(x=x).”Depending on a student’s background, a teacher might further compare this toequivalent syntax in other languages or to Python’s f-string syntaxf"{x=}".

To understand this, a student of Python would need to be familiar with thebasics of functions in addition to the existing keyword argument syntax.Given that this feature is a relatively straightforward syntactic sugar, it isreasonable that a student who possesses a grasp of keyword arguments will beable to absorb this concept quickly. This is evidenced by the success of thef-string syntax as well as similar features in other languages (seePrior Art).

Rejected Ideas

Many alternative syntaxes have been proposed however no form other thanf(=x) orf(x=) has garnered significant support. We here enumerate someof the most popular proposed alternatives and why we ultimately reject them.

f(a,b,*,x)

On a few occasions the idea has been floated to borrow the syntax fromkeyword-only function definitions.

In favour of this proposal:

  • This syntax is familiar from its use to require keyword-only arguments infunction definitions.
  • A poll of Python developersindicates that this is the second most popular syntax among those proposed.

However, we object that:

  • For any given argument, it is less clear from local context whether it ispositional or named. The* could easily be missed in a long argument listand named arguments may be read as positional or vice versa.
  • It is unclear whether keyword arguments for which the value was not elided mayfollow the*. If so, then their relative position will be confusinglyarbitrary, but if not, then an arbitrary grouping is enforced betweendifferent types of keyword arguments and reordering of arguments would benecessary if only one name (the argument or its value) was changed.
  • The use of* in function calls is well established and this proposal wouldintroduce a new effect which could cause confusion. For example,f(a,*x,y) would mean something different thanf(a,*,x,y).

f(=x)

In favour of this form:

  • The prefix operator is more similar to the established*args and**kwargs syntax for function calls.
  • It draws more attention to itself when arguments are arranged vertically. Inparticular, if the arguments are of different lengths it is harder to find theequals sign at the end. Moreover, since Python is read left to right, the useof this feature is clearer to the reader earlier on.

On the contrary:

  • While the prefix version is visually louder, in practice, there is no need forthis feature to shout its presence any more than a typical named argument. Bythe time we read to the= it is clear that the value is filled inautomatically just as the value is clear in the typical keyword argument case.
  • Semantically, this form communicates ‘here is a value, fill in the parameter’which is not what we want to convey.
  • It is less similar to f-string syntax.
  • It is less obvious that arbitrary expressions are invalid, for example,f(=a+b), since such expressions are acceptable after the equals sign inthe current keyword argument syntax but not before it.

f(%x) orf(:x) orf(.x)

Several flavours of this syntax have been proposed with the prefix formsubstituting another character for=. However, no such form has gainedtraction and the choice of symbol seems arbitrary compared to=.Additionally, there is less precedent in terms of existing language features(such as f-string) or other languages (such as Ruby).

Objections

There are only a few hard objections to the introduction of this syntacticsugar. Most of those not in favour of this feature are in the camp of ‘Iwouldn’t use it’. However, over the extensive conversations about this feature,the following objections were the most common:

The syntax is ugly

This objection is the most common. On the contrary, we argue that:

  • This objection is subjective and many community members disagree.
  • A nearly-identical syntax is already established for f-strings.
  • Programmers will, as ever, adjust over time.

The feature is confusing

We argue that:

  • Introducing new features typically has this impact temporarily.
  • The syntax is very similar to the establishedf'{x=}' syntax.
  • The feature and syntax are familiar from other popular modern languages.
  • The expansion ofx= tox=x is a trivial feature and inherentlysignificantly less complex than the popular*arg and**kwargexpansions.
  • This particular syntactic form has been independently proposed on numerousoccasions, indicating that it is the most obvious[1][2][6].

The feature is not explicit

We recognise that, in an obvious sense, the argument value is ‘implicit’ in thisproposed syntax. However, we do not think that this is what the Zen of Python isaiming to discourage.

In the sense that we take the Zen to be referring to, keyword arguments (forexample) are more explicit than positional arguments where the argument name isomitted and impossible to tell from the local context. Conversely, the syntacticsugar for integersx+=1 is not more implicit thanx=x+1 in thissense, even though the variable is omitted from the right hand side, because itis immediately obvious from the local context what it is.

The syntax proposed in this PEP is much more closely analogous to thex+=1example (although simpler since we do not propose to introduce a new operation).Moreover, by removing the barrier of visual noise introduced by the existingkeyword argument syntax, this syntactic sugar will encourage the use of keywordarguments over positional ones, making typical Python codebases more explicit ingeneral.

The feature adds another way of doing things

The same argument can be made against all syntax changes. This is a simplesyntactic sugar, much asx+=1 is sugar forx=x+1 whenx is aninteger. This isn’t tantamount to a ‘new way’ of passing arguments but a morereadable notation for the same way.

Renaming the variable in the calling context will break the code

ANameError would make the mistake clear in the large majority cases. Theremay be confusion if a variable from a broader scope has the same name as theoriginal variable, so noNameError would be raised. However, this issue canalso occur with keyword arguments using the current syntax (although arguably,this syntactic sugar could make it harder to spot). Moreover, having variableswith the same name in different scopes is broadly considered to be bad practiceand is discouraged by linters.

Code editors could highlight the issue based on static analysis –f(x=) isexactly equivalent to writingf(x=x). Ifx does not exist, moderneditors have no problem highlighting the issue.

This syntax increases coupling

We recognise that, as ever, all syntax has the potential for misuse and soshould be applied judiciously to improve codebases. In this case, if a parameterand its value have the same semantics in both contexts, that suggests that usingthis syntax is appropriate and will help ameliorate the risk of unintentionaldesynchronisation which harms readability.

However, if the two variables have different semantics, that suggests that thisfeature should not be used (since it encourages consistency) or perhaps that oneor both of the variables should be renamed.

Recommendations for Using This Syntax

As with any other language feature, the programmer should exercise their ownjudgement about whether it is prudent to use it in any given context. We do notrecommend enforcing a rule to use the feature in all cases where it may beapplicable, such as via lint rules or style guides.

As described inThis syntax increases coupling, we propose that a reasonablerule of thumb would be to use this in cases where a parameter and its argumenthave the same semantics in order to reduce unintentional desynchronisationwithout causing inappropriate coupling.

Impact on Editing

Using a plain text editor

Editing with a plain text editor should generally be unaffected.

When renaming a variable using a ‘Find-Replace’ method, where this syntax isused the developer will come across the function argument at invocation (as theywould if this syntax was not used). At that point, they can, as usual, decidewhether to update the argument as well or expand to the fullf(x=x) syntax.

As with the current syntax, a ‘Find-Replace All’ method would fail since thekeyword argument would not exist at function definition, in the vast majorityof cases.

If the developer leaves the argument name unchanged and forgets to update itsvalue, aNameError will typically be raised as described inRenaming the variable in the calling context will break the code.

Proposals for IDEs

In response to community feedback, we include some suggestions regarding howIDEs could handle this syntax. However, we defer to the domain expertsdeveloping IDEs to use their discretion.

Most considerations are made simple by recognising thatf(x=) is justsyntactic sugar forf(x=x) and should be treated the same as at present.

Highlighting NameErrors

IDEs typically offer a feature to highlight code that may cause aNameError.We recommend that this syntax be treated similarly to the expanded formf(x=x) to identify and highlight cases where the elided variable may notexist. What visual cue may be used to highlight these cases may be the same ordifferent from that which would be used with the current syntax, depending onthe IDE.

Jump to definition

There are a few possible ways that a ‘jump to definition’ feature could beimplemented depending on the caret/cursor position.

One option is to:

  • Jump to the argument in the function definition if the caret/cursor is on theargument
  • Jump to the definition of the elided variable if the caret/cursor is on thecharacter following the= in our proposed syntax

Another, potentially complementary, option would be to expand the syntaxvisually on mouseover and enable aCtrl+Click (orCmd+Click) to thedefinition of the variable.

Highlighting other references

IDEs frequently highlight matching code references to the value at the currentcaret/cursor position. With this shorthand syntax, when the caret/cursor is onthe argument name it may be valuable to either:

  • Highlight both references to the argument and its value reflecting the factthat this name now refers to both
  • Visually expand the syntax on mouseover (as above) and apply establishedhighlighting logic according to the cursor

Rename symbol

There are a few ways that IDEs may wish to support a ‘Rename symbol’ feature forthis syntax. For example, if the argument is being renamed, the IDE may:

  • Also rename the variable used as its value in each calling context where thissyntax is used
  • Expand to use the full syntax to pass the unchanged variable as the value ofthe renamed argument
  • Prompt the developer to select between the two above options

The last option seems to be the most preferable to reduce unintentionaldesynchronisation of names while highlighting the changes to the programmer.

Reference Implementation

A proposed implementationfor CPython has been provided by @Hels15. We will extend this implementation toadd an AST node attribute indicating for keywords whether the value was elided.Otherwise the AST will remain unchanged.

References

[1] (1,2,3)
Short form for keyword arguments and dicts (2013)https://mail.python.org/archives/list/python-ideas@python.org/thread/SQKZ273MYAY5WNIQRGEDLYTKVORVKNEZ/#LXMU22F63VPCF7CMQ4OQRH2CG6H7WCQ6
[2] (1,2,3)
Keyword arguments self-assignment (2020)https://mail.python.org/archives/list/python-ideas@python.org/thread/SIMIOC7OW6QKLJOTHJJVNNBDSXDE2SGV/
[3]
Shorthand notation of dict literal and function call (2020)https://discuss.python.org/t/shorthand-notation-of-dict-literal-and-function-call/5697/1
[4]
Allow identifiers as keyword arguments at function call site (extensionof PEP 3102?) (2023)https://discuss.python.org/t/allow-identifiers-as-keyword-arguments-at-function-call-site-extension-of-pep-3102/31677
[5]
Shorten Keyword Arguments with Implicit Notation: foo(a=a, b=b) to foo(.a, .b) (2023)https://discuss.python.org/t/shorten-keyword-arguments-with-implicit-notation-foo-a-a-b-b-to-foo-a-b/33080
[6] (1,2,3)
Syntactic sugar to encourage use of named arguments (2023)https://discuss.python.org/t/syntactic-sugar-to-encourage-use-of-named-arguments/36217

Copyright

This document is placed in the public domain or under theCC0-1.0-Universal license, whichever is more permissive.


Source:https://github.com/python/peps/blob/main/peps/pep-0736.rst

Last modified:2025-04-14 02:39:58 GMT


[8]ページ先頭

©2009-2025 Movatter.jp