Skip to content Skip to sidebar Skip to footer

Defining Lists As Global Variables In Python

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' i

Solution 1:

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

foo = []

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

Solution 2:

No, you can specify the list as a keyword argument to your function.

alist = []
deffn(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
deffn():
    foomodule.alist.append(1)
print foomodule.alist    # [1]

Post a Comment for "Defining Lists As Global Variables In Python"