- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
是否有别名函数参数的语法?如果没有,是否有任何 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/
对于NumericVector ,我可以将一个较小的 NumericVector 进行子集化通过使用 IntegerVector包含要子集化的位置。 例如假设x<-c(1,2,2,3,4,5) , i
我的 javascript 文件以配置开始... require.config({ baseUrl: 'scripts', paths: { 'code-mirror'
我的应用程序应该可以使用插件或通常称为糖的方式进行扩展。我会将它们放在 appname.app/Contents/sugars/sugarname.appnamesugar 下 这些是 bundle
我一直在尝试使用 Rcpp 在 C++ 中获取 vector 的等级。我使用了其他糖功能,例如 is_na(); C++中rank R函数有没有类似的糖函数。 Rcpp/ 中是否还有任何可用的 R 糖
我通过 Android Studio 使用 Sugar ORM 进行 Android 开发。 但我想我有一个非常相似的问题。如何将一个/多个结果查询显示为字符串或整数?我的实体看起来像这样: publ
入门读物: Prototypes as "classes" OO JS 按照上述模式,我创建如下库/API var Proto = { constructor: function () {
我在应用程序的第一个版本中使用了 SugarORM。现在,我正在开发第二个版本,它向数据库中添加了新表。 根据 SugarORM documentation “Sugar 会自动为新实体创建表,因此您
我是一名优秀的程序员,十分优秀!