0

I have seen other people ask a question but the only answers I have seen simply explain that python doesn't have the same concept of pass by reference vs pass by value as languages like C do. for example

    x=[0]
    def foo(x):
        x[0] += 1

In the past, I have been using this work around but it seems very un-pythonic so I'm wondering if there is a better way to do this. let's assume for what ever reason returning values won't work, like in the case where this code runs on a separate thread.

Supamee
  • 615
  • 5
  • 15
  • It's not that you cannot [technically hack Python](https://stackoverflow.com/a/45113210/7553525) to always 'pass by reference', tho. btw. Python always passes by reference in those terms (_reference_ is a vague concept when it comes to Python), it's just that certain properties are mutable and others are not - non-mutable properties utilize copy-on-write, tho, so you get the illusion they weren't passed by reference. – zwer Jul 19 '17 at 16:48
  • Python uses "pass by object", so neither pass by reference or value are applicable. You can use techniques like generators also. https://stackoverflow.com/questions/27034395/python-generator-vs-comprehension-and-pass-by-reference-vs-value – dmitryro Jul 19 '17 at 16:49
  • This looks like an [`XY problem`](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). You don't need to pass anything by reference, you need an [atomic counter](https://stackoverflow.com/a/35088370/6419007). – Eric Duminil Jul 19 '17 at 16:51
  • @EricDuminil sorry, This is not an XY problem, I only included that code to help illustrate the problem. I am somewhat new to SO and if you have an idea on how to better ask the question so this distinction is more apparent please edit – Supamee Jul 19 '17 at 16:59
  • 1
    There is no pass by reference. Did you think the people who told you Python doesn't support pass by reference were lying to you? – user2357112 Jul 19 '17 at 17:24

1 Answers1

2

Some python objects are immutable (tuple, int, float, str, etc). As you have noted, you cannot modify these in-place.

The best workaround is to not try to fake passing by reference, instead you should assign the result. This is both easier to read and less error prone.

In your case, you could call:

x = 0
def f(x):
    return x + 1

x = f(x)

If you truly need to fake passing by reference (and I don't see why you would need that), your solution works just fine, but keep in mind that you do not actually modify the object.

x = 0
x_list = [x]
print(id(x_list[0]))  # 1844716176

def f(x_list):
    x_list[0] += 1

f(x_list)
print(x)  # 0,  not modified
print(id(x_list[0]))  # 1844716208
Jonas Adler
  • 10,365
  • 5
  • 46
  • 73