有别名函数 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')