why functions in modules need 'global foo' for integer foo but not dictionary foo?
Paolino
paolo_veronelli at tiscali.it
Fri Jul 29 03:51:23 EDT 2005
Robert Kern wrote:
> seberino at spawar.navy.mil wrote:
>
>>At top of a module I have an integer like so...
>>
>>foo = 4
>>
>>In a function in that module I know I need to do 'global foo' to get at
>>the value 4.
>>...
>
>
> I presume you are trying code like the following:
>
> foo = 4
> bar = {}
>
> def fun1():
> foo = 5
>
> def fun2():
> bar['baz'] = 4
>
> Since integers are immutable, all that fun1() does is assign 5 to the
> name "foo" within fun1()'s namespace and doesn't touch the module-level
> namespace.
Hmm this is obscure to me also, what mutables has to do with this
problem?A binding is always mutable.
> fun2(), on the other hand, only gets the dictionary from the
> module-level namespace with the name "bar". Then it modifies that
> dictionary (since it's mutable). It does not try to assign a new object
> to the name "bar".
Probably the point is modifing/rebinding the bound values and not
rebind them.
Generally if you need to use globals for inter-instance/class
communication, I suggest to define a new namespace where
to put global bindings:
class Globals:
foo=4
spam={}
for lexical coherence you can put also funtions there
class Globals:
foo=4
spam={}
@staticmethod
def func():pass
then you always refer to them with Globals.foo,Globals.spam,Globals.func
or with <Module>.Globals.... from outside.
Finally consider to use singletons as a more common approach.
Ciao
___________________________________
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB
http://mail.yahoo.it
More information about the Python-list
mailing list