gpt4 book ai didi

Python 语法糖 : function arg aliases

转载 作者:太空宇宙 更新时间:2023-11-03 14:15:40 26 4
gpt4 key购买 nike

是否有别名函数参数的语法?如果没有,是否有任何 PEP 提案?我不是编程语言理论家,所以我的观点可能是无知的,但我认为实现某种函数 arg 别名可能很有用。

我正在对 libcloud 做一些更改我的想法将帮助我避免在更改 API 时破坏他人。

例如,假设我正在重构并想将函数参数“foo”重命名为“bar”:

原文:

def fn(foo):
<code (using 'foo')>

我可以:

def fn(foo, bar=None):
if foo and bar:
raise Exception('Please use foo and bar mutually exclusively.')
bar = foo or bar
<code (using 'bar')>

# But this is undesirable because it changes the method signature to allow
# a new parameter slot.
fn('hello world', 'goodbye world')

我未提炼的语法糖想法:

def fn(bar|foo|baz):
# Callers can use foo, bar, or baz, but only the leftmost arg name
# is used in the method code block. In this case, it would be bar.
# The python runtime would enforce mutual exclusion between foo,
# bar, and baz.
<code (using 'bar')>

# Valid uses:
fn(foo='hello world')
fn(bar='hello world')
fn(baz='hello world')
fn('hello world')

# Invalid uses (would raise some exception):
fn(foo='hello world', bar='goodbye world')
fn('hello world', baz='goodbye world')

最佳答案

不,没有这样的语法糖。

您可以使用 **kwargs 来捕获额外的关键字参数并在其中查找已弃用的名称(如果不存在则引发异常)。您甚至可以使用装饰器将其自动化。

from functools import wraps

def renamed_argument(old_name, new_name):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if old_name in kwargs:
if new_name in kwargs:
raise ValueError(
"Can't use both the old name {} and new name {}. "
"The new name is preferred.".format(old_name, new_name))
kwargs[new_name] = kwargs.pop(old_name)
return func(*args, **kwargs)
return wrapper
return decorator

@renamed_argument('bar', 'foo')
def fn(foo=None):
<method code>

演示:

>>> @renamed_argument('bar', 'foo')
... def fn(foo=None):
... return foo
...
>>> fn() # default None returned
>>> fn(foo='spam')
'spam'
>>> fn(bar='spam')
'spam'
>>> fn(foo='eggs', bar='spam')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in wrapper
ValueError: Can't use both the old name bar and new name foo. The new name is preferred.

关于Python 语法糖 : function arg aliases,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33556673/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com