Pass by reference

iu2 israelu at elbit.co.il
Wed Dec 31 12:30:11 CET 2008


Hi,

Is it possible somehow to change a varible by passing it to a
function?

I tried this:

def change_var(dict0, varname, val):
  dict0[varname] = val


def test():
  a = 100
  change_var(locals(), 'a', 3)
  print a


But test() didn't work, the value a remains 100.

I have several variables initialized to None.
I need to convert each one of them an object only if it is None.
something like:

if not var1: var1 = MyObject()

I want this to be a function, that is:

def create_obj(var):
  if not var: var = MyObj()
  # set properties of var

Now, I know I can achieve this by functional programming,

def create_obj(var):
  if not var:
    x = MyObj()
    # set properties of x
    return x
  return var

and then

var = creaet_obj(var)

Is there another way?

Thanks



More information about the Python-list mailing list