modifing function's parameters global value

Chad Netzer cnetzer at mail.arc.nasa.gov
Tue May 13 15:04:59 EDT 2003


On Tue, 2003-05-13 at 11:16, Federico wrote:
> Here is an example:
> 
> x=1
> def func(y):
>     y=y+1
>     print y
> print x
> func(x)
> print x

> there is no way to modify a parameter in a function? In C I used pointers...

There are ways, but doing things this way is considered awful practice. 
Even in C, when it is done, it is mainly because C is less flexible
about return types.

You can do this instead:

def func(y):
   return y + 1

x = 1
x = func( x )
print x

This will print the value '2'.  Note that func does not have side
effects.  If you really NEED side effects, you can pass values in a
dict, or list, or class instance, etc.

However, please note this variation:

def func2(a, b):
   return (a+1, b+2)

x,y = func2(1,1)
print x,y

This will print "2 3", and illustrates the powerful idea that you can
return multiple values from a function in Python, without having to wrap
them in a C "struct" like object.  This eliminates nearly ALL the needs
you might ever have for using side-effect like behavior in functions[1].

The only time functions should ever have side-effect behavior in Python,
is when they are member functions of an instance or class, and thus, are
changing the state of their associated object.  Indeed, that is an all
important feature of object based computing.  Standalone functions
should always take in values, and return values, and not change things
that aren't explicitly returned (The holds for C, too, btw, but C
doesn't support the idea very well for complex operations)

[1] - Note that these "rules" are meant to be broken when necessary, and
with the use of "generators" in Python, side-effect behavior is put to
good use.  Cross that bridge when you get to it.

Hope this advice helps.

-- 

Chad Netzer
(any opinion expressed is my own and not NASA's or my employer's)






More information about the Python-list mailing list