1

I have seen other questions related to this topic, but haven't really found an answer to the following simple problem:

VB Code:

Function f_x(ByRef x As Integer)

    x = x + 1

End Function

Sub test()

    Dim w As Integer
    w = 2

    Call f_x(w)

    MsgBox w

End Sub

The output above is 3, whereby the variable "w" is modified through the pointer "x" inside the function "F_x()" (i.e. "by reference").

Can I write a similar function in Python, which modifies a single numerical variable through a pointer (i.e. "by reference")? I understand that a list or a Numpy array will be modified (automatically) by reference when passed to a function, but what about a single numerical variable?

EDIT: as per suggestion below, I am adding my attempt to code this in Python (which obviously doesn't work):

def test_function(y):
    y = y + 1

x = 2 
test_function(x) 
print(x)

The output above is 2, not 3.

Edit 2: why on earth would anyone bother with choosing whether to pass a numerical variable by reference (through a pointer) or by value? What if the task is to write a computationally efficient code and one is dealing with large floating point numbers: here, a pointer ("by reference") will only need to store the memory address, whilst "by value" approach will have to "copy" the entire variable inside the function.

8
  • 1
    You should try to write it in Python and come here and ask when it doesn't work. Not post a VB code tagged as Python... Commented Jun 15, 2020 at 9:59
  • No, python does not support call by reference. Commented Jun 15, 2020 at 10:02
  • 2
    @JanStuller The simple answer is just "No, it's not possile". Python does not support something like VB's "ByRef ". Commented Jun 15, 2020 at 11:25
  • 1
    Because someone removed it, here is the duplicate: stackoverflow.com/questions/986006/… Commented Jun 15, 2020 at 13:50
  • 1
    Python doesn't support call by ref, but you could have a wrapper object for your variable. You can then pass the object to your function and the function has to modify your value. E.G. test_function(obj) where test_function executes: obj.y += 1 Commented Jun 15, 2020 at 14:13

1 Answer 1

4

You could put your variable in a mutable object like a dict:

def test_function(y):
    y['x'] = y['x'] + 1

d = {'x': 2} 
test_function(d) 
print(d['x'])

Primitive types are immutable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.