[Tutor] global list

Steven D'Aprano steve at pearwood.info
Fri Apr 25 06:46:33 CEST 2014


On Thu, Apr 24, 2014 at 01:14:33AM -0700, Albert-Jan Roskam wrote:

> ----- Original Message -----
> > From: Steven D'Aprano <steve at pearwood.info>
> > To: tutor at python.org
> > Cc: 
> > Sent: Thursday, April 24, 2014 3:00 AM
> > Subject: Re: [Tutor] global list
> > 
> 
> <snip>
> 
> > You only need to define variables as global if you assign to them:
> > 
> > def function(x):
> >     global a
> >     a = [1, 2, 3, x]  # assignment to variable "a"
> 
> ah, thanks, I always wondered about that. But doesn't it make the 
> function (slightly) faster if you use 'global' when you only refer to 
> that global variable? 

Theoretically, but not in practice. In Python 2.7, for example, you get 
exactly the same byte-code whether you declare it global or not:

py> from dis import dis
py> def test():
...     global a
...     return a + b
...
py> dis(test)
  3           0 LOAD_GLOBAL              0 (a)
              3 LOAD_GLOBAL              1 (b)
              6 BINARY_ADD
              7 RETURN_VALUE

CPython, at least (I'm not sure about Jython and IronPython) doesn't 
bother checking locals for variables it already knows must be global, so 
there's no slowdown there.

In principle an optimizing Python might be able to recognise when you're 
referring to a built-in, and avoid needlessly checking for a global of 
the same name, but that's actually quite a hard thing to get right.


> You tell the interpreter that it is not needed 
> to search for that variable locally, so no time wasted on that.

It's actually the other way around: you tell Python that a variable is 
local by assigning to it, in which case it is *only* looked for in the 
locals. Otherwise locals are always skipped.

(The handling of locals() in Python 2 is a bit tricky, and there are 
differences between CPython, Jython and IronPython when you use exec or 
import * inside a function. Python 3 simplifies the odd corner cases by 
disallowing those troublesome cases.)


>  The 
> code below indicates that it makes NO difference (well, a whopping 
> 2ns), but maybe for larger functions it does?

I wouldn't expect that 2ns is meaningful. I would treat it as mere noise 
in the measurement.



-- 
Steven


More information about the Tutor mailing list