Python语法糖:函数arg别名

笨拙1

别名函数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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

别名中 bash 函数的语法问题

来自分类Dev

信号插槽的语法糖

来自分类Dev

VBA语法糖

来自分类Dev

构造函数参数列表和继承字段上的this.field语法糖。

来自分类Dev

使用Pythonic方式,语法糖还是运算符将函数应用于自身?

来自分类Dev

棉花糖:如何覆盖此python类的构造函数?

来自分类Dev

是build_语法糖吗?

来自分类Dev

做语法糖和赋值

来自分类Dev

pentadactyl-命令的语法糖

来自分类Dev

语法糖的Haskell剥离功能

来自分类Dev

IN 语法糖来自 = ANY 吗?

来自分类Dev

python语法错误* args带有可选的arg

来自分类Dev

Python语法:函数参数中的“ for”

来自分类Dev

如何在不使用语法糖的情况下实例化Python列表

来自分类Dev

列表理解是Python 3中`list(generator expression)`的语法糖吗?

来自分类Dev

属性装饰器如何在python中使用语法糖(@)在内部工作?

来自分类Dev

嵌套self .__ parent __.__ parent__的Python快捷方式(语法糖)。

来自分类Dev

VALUES()语法的列别名

来自分类Dev

bash别名定义的语法

来自分类Dev

任何函数式编程语言都具有用于更改对象部分的语法糖吗?

来自分类Dev

Swift中init属性的语法糖?

来自分类Dev

通用lambda:语法糖还是不是?

来自分类Dev

Scala-tuple3-语法糖

来自分类Dev

将面膜涂到多行上(语法糖?)

来自分类Dev

如何迅速制作自己的语法糖?

来自分类Dev

Lua中语法糖(冒号)的奇怪行为

来自分类Dev

语法糖与模式匹配的非穷尽模式

来自分类Dev

if(!result)返回false的C ++糖语法;

来自分类Dev

是-如果不是-只是语法糖吗?