[Tutor] Comments appreciated

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Dec 27 10:00:35 CET 2004



[Jacob]
> > BTW, trashcan IS a module level variable because it's defined at the
> > module level. Why it says it's local is beyond me.

[Danny]
> Ah, you must be running into the global/local gotcha.

[long rambling text cut]

Wait, wait.  Forget everything I said.  *grin* I should have read the
question more closely before going crazy with the explanation.  I think I
screwed up again.  Luis, please forgive me for not reading that more
closely.


Let me read Luis's message again... ok.  I think I understand where I got
confused.  Let's start over.  Let me write another rambling post.


Let's repeat the conversation, starting from Jeff's response:

[Jeff]
> Also, even though this is intended to be a quick shell script, it's
> not a bad idea to make everything except function defs into a little
> main() function, and call it in a script-only section.


[Luis]

> The only thing I'm not clear about is how 'trashcan' can be a
> local variable inside main() when it's required by both trash() and
> can()


What Jeff is trying to say is that it's possible to pass 'trashcan' around
as yet another parameter to both trash() and can().  That is, we can avoid
global variables altogether, and just work with parameter passing.


As a concrete example, the following program:

###
password = "elbereth"

def guess():
    msg = raw_input("try to guess: ")
    if msg == password:
        print "You got it!"
    else:
        print "nope"

def main():
    guess()

if __name__ == '__main__':
    main()
###


can be transformed so that it uses no global variables.  We can do this by
making guess() take in 'password' as a parameter too:

###
def guess(password):
    msg = raw_input("try to guess: ")
    if msg == password:
        print "You got it!"
    else:
        print "nope"

def main():
    pword = 'elbereth'
    guess(pword)

if __name__ == '__main__':
    main()
###

No more globals.  The password is now explicitely passed between the
main() and the guess().


An advantage here is that this guess() function is less tied to outside
global resources, and is, in theory, more easily reused.  If we wanted to
rewrite the program so that we take three different passwords, the version
without global variables is easy to write:

    guess("elbereth")
    guess("open sesame")
    guess("42")

But the one with the global variable use is something much uglier on our
hands:

    password = "elbereth"
    guess()
    password = "open sesame"
    guess()
    password = "42"
    guess()


Anyway, sorry about the confusion.  I have to read threads more carefully!


Best of wishes!



More information about the Tutor mailing list