2

In this example (which does not work)

def foo(x,y):
   x = 42
   y = y * 2

x = 0
y = 2
foo(x,y)

I would like x = 42 and y = 4.

The idea behind is to have a wrapper to C functions using ctypes:

def foo(self, x, y):
    error = self.dll.foo(self.handler, x, pointer(y))
    if error: 
       self.exception(error)

How can I pass parameters as references in Python?

4
  • 1
    You cannot pass primitive values by reference, unless you wrap or box the variables into non-primitive objects (i.e., classes or lists) which are always passed by references. Commented Sep 2, 2015 at 8:28
  • 1
    at least get the example right... Commented Sep 2, 2015 at 8:28
  • you have a typo in foo x = y * 2 should be y *= 2 Commented Sep 2, 2015 at 8:29
  • stackoverflow.com/questions/986006/… u will get detail from here about pass by reference in python. Commented Sep 2, 2015 at 8:35

1 Answer 1

3

Like @musically_ut, you cannot pass primitive values by reference, but you can get newest values by returning from function. Like this:

def foo(x,y):
   x = 42
   y = y * 2
   return x,y

x = 0
y = 2
x,y=foo(x,y)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.