Passing by reference

MartinRinehart at gmail.com MartinRinehart at gmail.com
Fri Dec 21 07:57:36 EST 2007



Sion Arrowsmith wrote:
> Michael Sparks  <ms at cerenity.org> wrote:
> >def bar():
> >    global x
> >    x[0] += " another"
> >    print id(x[0])
>
> ... and for bonus marks, explain why the "global x" in this function
> is not required.

Because x does not appear as an LHS in bar(), just about the first
thing I learned here.

More seriously, I can and do use lots of globals. In the tokenizer I'm
writing, for example, all the token types(COMMENT_EOL = 0,
CONSTANT_INTEGER = 1, ...) are global constants. The text to be
tokenized is a global variable. (Actually, the text is unchanging once
the Tok object is created, so this "variable" may be another
constant.) Passing global constants to functions is a case of CPU
abuse.

Structured purists gave globals a bad rap, years ago. Time to stick up
for them. They're good citizens. Don't blame them if some dumb coder
abuses them. It's not their fault.



More information about the Python-list mailing list