Python 中的变异/就地函数调用或改编

Mutating / in-place function invokation or adaptation in Python

我的代码中经常有执行以下操作的语句:

long_descriptive_variable_name = some_function(long_descriptive_variable_name)

这很清楚,但同时又冗长又有些多余。 Python 中是否有任何方法可以通过使 some_function 充当 "mutating" ("in-place") 函数来简化此语句?

例如,在 Julia one can often do 中如下:

some_function!(long_descriptive_variable_name)

并将其分派到直接写入 long_descriptive_variable_namesome_function 版本,有效更新变量。

有没有什么方法可以在 Python 中简洁地表达通用函数 some_function 中的相同内容?

用一般的对象方法做同样的事情怎么样?即简化

long_variable_name = long_variable_name.method(arg1, arg2)

如果上述 Python 的当前版本无法(轻松)实现,是否有任何 PEP 在不久的将来考虑此更改?

你要求的可以这样实现,但我当然不建议这样做:

>>> x = 10
>>> def foo(func, string_of_var):
    globals()[string_of_var] = func(globals()[string_of_var])

>>> def bar(x):
    return x * 2

>>> foo(bar, 'x')
>>> x
20

至于更改它的 PEP,我怀疑它是否会获得批准。像这样调用隐式更改值的函数违背了 Python:

的禅宗
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.  <==== Relevant line
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.  <==== also probably relevant
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.  <==== And this one for good measure
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

这也可能需要相当多的工作而不会给语言增加太多。 Python 没有 this reason++/--。当 x += 1 达到同样的效果时,添加它会做更多的工作。这里也是一样,调用函数的时候少敲几下键盘,几个人的功夫可不小。

免责声明:这不应该用在任何严肃的代码中,我写它只是为了好玩,甚至不认为它很聪明。

不确定这是否是您想要的(如果跑题了请见谅),但我在创作时真的很开心。

class FancyThing(object):

    def __init__(self, value):

        self.value = value

    def update(self, callback):

        self.value = callback(self.value)

    def __get__(self, instance, owner):

        return instance.value

    def __set__(self, instance, value):

        instance.value = value

    def __str__(self):

        return str(self.value)

    def __add__(self, other):

        return self.value + other

如果您在此 class 中包装一些内容,您可以 update 使用任何随机回调。

def some_func(val):
    return val * 3

a = FancyThing(3.5)
print a

a.update(tester)
print a
b = a + 5
print b

输出:

3.5
10.5
15.5

有趣的是,你必须定义 lots 的内置方法才能像普通方法一样使用内部值,就像我为 [=14 所做的那样=].