How do I make list global please?

Thomas Wouters thomas at xs4all.net
Sun Apr 30 06:15:44 EDT 2000


On Sun, Apr 30, 2000 at 07:42:59PM +1000, cmfinlay at SPAMmagnet.com.au wrote:
> How do I make list global please?
> 
> I have a list which comprise of mags[0] and mags[1]
> I want to pass and return it from a subroutine.
> my code is (in two text files)
> 
> 
> from inittest import InitTest
> mags = [333]
> mags.remove(333)
> mags.append(0) # (Big) array of magnets
> mags.append(1) # (Big) array of magnets
> print mags[0]
> print mags[1]
> InitTest()
> print mags[0]
> print mags[1]
> 
> # file :inittest.py
> def InitTest():
>    global mags
>    print "I am in the Sub"
>    Print mags[0]
>    Print mags[1]
>    print "Leaving Sub"
>    return
> 
> I get the error message
> QUOTE
> Traceback (innermost last):
>   File "inittest1.py", line 1, in ?
>     from inittest import InitTest
>   File "inittest.py", line 5
>     Print mags[0]
> SyntaxError: invalid syntax

You actually have 2 problems: One is typing 'Print' instead of 'print';
Python is case-sensitive, which causes the SyntaxError message you see. The
other problem is your real problem, you dont define 'mags' anywhere in your
inittest.py file. The 'global' statement doesn't do what you expect it to do
(it makes the variables global even if you assign to them. Normally
variables you assign to are always local, whereas variables you only read
from are read globally only if they dont exist locally.)

Your problem is not that 'mags' is global, not local, but that 'mags' is
undefined completely. The 'inittest.py' file doesn't know what it should be,
where it should come from, etc. You can do two things: in inittest.py,
import the first file (which creates a circular dependancy, never a good
thing) or (much better) pass InitTest the list to work on, like so:

from inittest import InitTest
mags = [333]
mags.remove(333)
mags.append(0) # (Big) array of magnets
mags.append(1) # (Big) array of magnets
print mags[0]
print mags[1]
InitTest(mags)
print mags[0]
print mags[1]

# file :inittest.py
def InitTest(mags):
    print "I am in the Sub"
    Print mags[0]
    Print mags[1]
    print "Leaving Sub"
    return

You can change the name of 'mags' in the 2nd file, of course.

> my code works when it is all in the main routine.

Yes, it would (barring the Print/print thing) -- but you wouldn't need the
'global' statement, as you dont assign to mags, you only modify mags.

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list