25

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 "global" in all the functions?

I mean putting the global keyword behind it in each function that uses it, or defining it outside of all the functions is enough without using the global word behind its definition?

1
  • 5
    Of course you do know that global variables are eeeevil? When possible, don't write function that depend on anything other than the arguments. And never, unless in very rare circumstances, modify something global from more than one point. It's nearly never necessary and is prone to adding huge headaches later. In conclusion, not worth it. Commented Jan 7, 2011 at 21:46

3 Answers 3

37

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).

Sign up to request clarification or add additional context in comments.

2 Comments

+1. It's also worth noting that slice assignments will not overwrite the reference. In particular, instead of x = newlist, one can do x[:] = new_list and still have no need for using global. This is of course covered under the method call case but it's worth pointing out explicitly.
@aaron: Yes. Expanded to make clear that there are numerous things (including member assignment, slice assignment, etc) are actually method calls.
12

Yes, you need to use global foo if you are going to write to it.

foo = []

def bar():
    global foo
    ...
    foo = [1]

2 Comments

While not strictly wrong (in the example, the global is necessary), this is misleading. For starters, many seem to disagree with Python's notion of when you "write to it".
@Hossein: It's the same for any variable. The object referenced doesn't matter.
2

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]

2 Comments

Clarification: "Globals" are always module-level. No need to put it into an extra module (sometimes useful or semantically more correct though).
I wasn't aware of the intricacies involved. Seems the two examples that I wrote are not necessary at all if all you want to do is modify a module level variable (that is, not make an assignment to the global name). See delnan's answer for a much better assessment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.