[Tutor] mutable strings? [and global stuff]

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 23 Mar 2001 08:08:42 -0800 (PST)


On Fri, 23 Mar 2001, Scott wrote:

> What is the procedure to use if you want a couple of global, mutable,
> string-like objects?

Strings are immutable, but from your previous post, it looks like you've
found out about using mutable lists; that's one way of doing it.  Could
you tell us the context of the program you're writing, or is your question
just to explore?

About global stuff... there's some pitfalls that we need to talk about:
Any variable defined outside of a function definition is global, and any
variable defined inside is local.  Simple enough, but you'll run into a
few snags here and there:

###
myglobal = 'a'

def test():
    print myglobal
###

This works as you might expect, but:

###
myglobal = 'a'

def test():
    print myglobal
    myglobal = 'z'
    print myglobal
###

does _not_ work; the reason is because, within test(), Python senses that
we're doing an assignment of 'myglobal', so it thinks that it must be a
local variable.  (You'll run into one of the weirder error messages that
myglobal isn't defined with test()!)  Most python programs want
local-scope, which is why you'll run into some problems when dealing with
globals.  What we need to do is label 'myglobal' as a global:

###
myglobal = 'a'

def test():
    global myglobal
    print myglobal
    myglobal = 'z'
    print myglobal
###

What was that term for the phenomena that happens when you say a word over
and over, till it loses its meaning?  Global global global global global.  
Sorry about that.  *grin*

(Personally, I try to avoid globals as much as possible, so that's why I'm
a little hesitant --- I haven't concienciously made a global variable for
a while.  *grin*)