I am using a list on which some functions works in my program. This is a shared list actually and all of my functions can edit it. Is it really necessary to define it as \"g
No, you can specify the list as a keyword argument to your function.
alist = []
def fn(alist=alist):
alist.append(1)
fn()
print alist # [1]
I'd say it's bad practice though. Kind of too hackish. If you really need to use a globally available singleton-like data structure, I'd use the module level variable approach, i.e. put 'alist' in a module and then in your other modules import that variable:
In file foomodule.py:
alist = []
In file barmodule.py:
import foomodule
def fn():
foomodule.alist.append(1)
print foomodule.alist # [1]
When you assign a variable (x = ...
), you are creating a variable in the current scope (e.g. local to the current function). If it happens to shadow a variable fron an outer (e.g. global) scope, well too bad - Python doesn't care (and that's a good thing). So you can't do this:
x = 0
def f():
x = 1
f()
print x #=>0
and expect 1
. Instead, you need do declare that you intend to use the global x
:
x = 0
def f():
global x
x = 1
f()
print x #=>1
But note that assignment of a variable is very different from method calls. You can always call methods on anything in scope - e.g. on variables that come from an outer (e.g. the global) scope because nothing local shadows them.
Also very important: Member assignment (x.name = ...
), item assignment (collection[key] = ...
), slice assignment (sliceable[start:end] = ...
) and propably more are all method calls as well! And therefore you don't need global
to change a global's members or call it methods (even when they mutate the object).
Yes, you need to use global foo
if you are going to write to it.
foo = []
def bar():
global foo
...
foo = [1]