Pass by reference

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Wed Dec 31 06:59:18 EST 2008


iu2 a écrit :
> Hi,
> 
> Is it possible somehow to change a varible by passing it to a
> function?

For which definition of "change a variable" ?

> I tried this:
> 
> def change_var(dict0, varname, val):
>   dict0[varname] = val

Ok, this is mutating dict0, so it works.

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

Please (re)read the doc for locals():
http://www.python.org/doc/2.6/library/functions.html#locals

See the big warning ?

>   print a


> 
> But test() didn't work,

It did. The problem is elsewhere.

> the value a remains 100.
> 
> I have several variables initialized to None.

Where ?

> I need to convert each one of them an object only if it is None.
> something like:
> 
> if not var1: var1 = MyObject()

Warning : some objects can eval to false in a boolean context without 
being None. Better to explicitely test identity here:

if var1 is None:
     var1 = Something()


> I want this to be a function, that is:
> 
> def create_obj(var):
>   if not var: var = MyObj()

This is a rebinding, not a mutation. Here, 'var' is a local *name*, so 
rebinding it will only affect the local namespace.

>   # set properties of var

Why don't you use the initializer of MyObj here ?

class MyObj(object):
     def __init__(self, prop1, propx):
         # set properties of self
         self.prop1 = prop1
         self.propx = propx


Then just call:

var = MyObj(somevalue, someothervalue)

> 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

This is just a plain function. You may want to re-read the definition of 
"functional programming" !-)

> and then
> 
> var = creaet_obj(var)
> 
> Is there another way?

What's wrong with this one ?




More information about the Python-list mailing list