On Dec 31, 5:30 am, iu2 <isra...@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. > > 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
A practical way is to use a container. Some people use lists; I like an object. thingref= Ref( thing ) f( thingref ) print thingref() #or thingref.get() or w'ver. Then 'f' can assign like this: def f( aref ): # blah blah aref( newthing ) #or aref.set( newthing ) But the short answer is no. A function receives the contents of a variable, not a variable. -- http://mail.python.org/mailman/listinfo/python-list