开发者

Python: variables by references (hack)

开发者 https://www.devze.com 2023-04-09 02:39 出处:网络
Is there any way (hack) to push Python function (def) to return results by reference even for immutable types?

Is there any way (hack) to push Python function (def) to return results by reference even for immutable types?

A proposal application (swap as subroutine):

def swap(a, b):

.....a,b = b,a

Note:

def swap(a, b):

.....return b,a

works as function which is not the answer of the question!


For example there is a function random.shuffle(a) that works in-place. My idea is to c开发者_如何学Pythonall a function written in Fortran/C++ and call them via Python. It does work but has disadvantages too.

note:

Both "lambda" and "def" (as function) have the following problem: a, b = swap(a, b) which requires care about order of variables. In my proposal (if it was possible) the subroutine is used as: swap(a, b) so there is no requirement to care about order of variable.


All names in Python are references. And no, there are no "out" references (e.g. in a C++ sense) available. You need to pass a mutable object and then you can mutate it in the function. But then again, returning new value(s) should be the preferred way.


No, such things don't exist, because you get the given object as a reference, but if you re-assign it, it won't be changed back.

You either have to work with a mutable container (list, dict, object with attributes) in this case.


In python there is no way to pass a "write pointer". You can pass an object and a name (so the callee can use for example setattr) or you can pass a list and an index. There is no such a thing as a context free "address of a modifiable cell"... there are only names or indexes that however also need a context (which namespace, which array).

In the general case if you really need to pass a write pointer a solution in Python is to pass a "setter" function that can be used by the callee to set the value.

For example:

def foo(setter):
    setter(42)

def bar():
    x = [1,2,3,4]

    def setFirst(value):
        x[0] = value

    foo(setFirst)

    print x[0] # --> 42
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号