别名函数args有语法吗?如果没有,是否有任何PEP建议?我不是编程语言理论家,所以我的看法可能不为人所知,但是我认为实现某种函数arg别名可能会有用。
我正在对libcloud进行一些更改,我的想法将帮助我避免在更改API时破坏其他内容。
例如,假设我正在重构,并想将函数arg'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来做到这一点:
def fn (**kw):
arg = kw.get("foo") or kw.get("bar") or kw.get("baz")
if arg==None: raise TypeError, "foo nor bar nor baz given az argument"
print arg
Here the order of precedence is: "if foo exists, arg is foo. if it doesn't but bar exists, arg is bar, if neither foo nor bar exists, the arg is baz. If baz doesn't, i.e. all 3 are missing, arg is None.
Of course, you may check whether either one exists and force the mutual exclusion, but I don't see why would you need such a thing.
You are clever and you will never pass them in together. Even if you do, some will be ignored.
您也可以使用可调用对象来执行此操作,甚至可以在运行时将语法和行为引入解释器。
但是我认为,将其作为有效的Python语法引入并不是Python的,即使有PEP,也永远不会发生。
如您所见,您可以执行所需的操作而不会弄脏Python语法。
我并不是说您的例子在语法上不明确,只是不必要。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句