Pass by reference

Chris Rebert clp at rebertia.com
Wed Dec 31 06:48:49 EST 2008


On Wed, Dec 31, 2008 at 3:30 AM, iu2 <israelu at elbit.co.il> wrote:
> 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.

Yes, that's clearly stated in the documentation for locals(); from
http://docs.python.org/library/functions.html#locals :

"Warning: The contents of this dictionary should not be modified;
changes may not affect the values of local variables used by the
interpreter."

>
> 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()

That should be:

if var1 is None: var1 = MyObject()

Otherwise, the "conversion" will also happen if var1 happens to be a
false but non-None object, e.g. {}, [], 0, etc
Also, it's just the idiomatic way of writing tests against None in Python.

>
> 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?

Not really, or at the very least it'll be kludgey. Python uses
call-by-object (http://effbot.org/zone/call-by-object.htm), not
call-by-value or call-by-reference.

Could you explain why you have to set so many variables to the same
value (if they're None)? It's a bit strange and could be a sign that
there's a better way to structure your program (e.g. use a
dictionary). We might be able to offer more helpful suggestions if you
explain.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list