Passing by reference

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Dec 21 08:42:13 EST 2007


MartinRinehart at gmail.com a écrit :
> 
> 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.

We all do, FWIW - since everything is name/object binding, all the 
classes, functions, modules etc defined or imported in a module are, 
technically, globals (for the Python definition of 'global').

> In the tokenizer I'm
> writing, for example, all the token types(COMMENT_EOL = 0,
> CONSTANT_INTEGER = 1, ...) are global constants.

Technically, they are not even constants !-)

> The text to be
> tokenized is a global variable. 

Now *this* is bad. Really bad.

> (Actually, the text is unchanging once
> the Tok object is created, so this "variable" may be another
> constant.) 

It isn't.

> Passing global constants to functions is a case of CPU
> abuse.

Remember that Python doesn't copy objects when passing them as function 
params, and that function-local names are faster to lookup than global 
ones.

There are indeed reasons not to pass module constants to the module's 
functions, but that have nothing to do with CPU. And in your case, the 
text to be tokenised is definitively not a constant.

> 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. 

Once you learned why you should not do something - and how to avoid 
doing it -, chances are you also know when it's ok to break the rule.



More information about the Python-list mailing list