reference or pointer to some object?

Peter Maas peter at somewhere.com
Tue Jan 11 15:08:40 EST 2005


Torsten Mohr schrieb:
> i'd like to pass a reference or a pointer to an object
> to a function.  The function should then change the
> object and the changes should be visible in the calling
> function.
[..]
> is something like this possible in python?

Yes, wrap it in a container, e.g. a list or an object.
Change the containers content in the called function.

> The keyword "global" does NOT fit this purpose to
> my understanding as it only makes the variables of
> the UPPERMOST level visible, not the ones of ONE
> calling level above.

There are three namespaces in python, sorted according to
priority:

- local
   variables of the current scope (function or method),
   highest priority, show with locals()

- global
   variables of the containing module, show with globals()

- builtin
   builtin variables, show with __builtins__.__dict__

Since Python 2.1 the local namespace can be nested e.g. if
a function is defined inside a function. Example:

 >>> def fo(u):
... 	def fi(v):
... 		v2 = 2*v
... 		print locals()
... 		return v2
... 	u2 = fi(u)
... 	print locals()
... 	return u2
...
 >>> fo(4)
{'v2': 8, 'v': 4}      <-- inner local namespace
{'fi': <function fi at 0x011AEBB0>, 'u': 4, 'u2': 8} <-- outer local namespace
8


-- 
-------------------------------------------------------------------
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
-------------------------------------------------------------------



More information about the Python-list mailing list