Scope

Peter Dembinski pdemb at gazeta.pl
Sat Jun 4 13:55:05 EDT 2005


Elliot Temple <curi at curi.us> writes:

> I want to write a function, foo, so the following works:
>
> def main():
>      n = 4
>      foo(n)
>      print n
>
> #it prints 7
>
> if foo needs to take different arguments, that'd be alright.
>
> Is this possible?

It is possible, but the more natural way would be to use function
return value:

   n = f(n)

or, if you need many assignments:

   a, b, c, d = f(a, b, c, d)

and, respectively:
   
   return a, b, c, d

in the function's body.

> I already tried this (below), which doesn't work.  foo only changes
> the global n.
>
>
> n = 3
> def main():
>      def foo(var, context, c2):
>          exec var + " = 7" in context, c2
>
>      n = 4
>      foo("n", locals(), globals())
>      print n
>
> if __name__ == '__main__': main()
>
> print n

You need to make 'n' globally visible.  See the 'global' keyword 
in Python user manual.

> And of course I tried:
>
>  >>> def inc(n):
> ...  n += 3
> ...
>  >>> a = 4
>  >>> inc(a)
>  >>> a
> 4

AFAIK inc is builtin function.  And builtin functions doesn't have to
be real functions, they can be just aliases to Python's VM bytecodes
or sets of bytecodes.



More information about the Python-list mailing list