[Tutor] global list
Peter Otten
__peter__ at web.de
Thu Apr 24 13:49:39 CEST 2014
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? You tell the interpreter that it is not needed to search for
> that variable locally, so no time wasted on that. The code below indicates
> that it makes NO difference (well, a whopping 2ns), but maybe for larger
> functions it does?
>
> albertjan at debian:~$ ipython
> Python 2.7.3 (default, Mar 13 2014, 11:03:55)
>
> In [1]: a = True
>
> In [2]: def function():
> ...: x = True if a else False
> ...:
>
> In [3]: %timeit function()
> 10000000 loops, best of 3: 122 ns per loop
>
> In [4]: def function():
> ...: global a
> ...: x = True if a else False
> ...:
>
> In [5]: %timeit function()
>
> 10000000 loops, best of 3: 120 ns per loop
For functions whether a is global or not is determined at compile-time. Have
a look at the byte code for your functions:
>>> def f():
... x = True if a else False
...
>>> def g():
... global a
... x = True if a else False
...
>>> dis.dis(f)
2 0 LOAD_GLOBAL 0 (a)
3 POP_JUMP_IF_FALSE 12
6 LOAD_CONST 1 (True)
9 JUMP_FORWARD 3 (to 15)
>> 12 LOAD_CONST 2 (False)
>> 15 STORE_FAST 0 (x)
18 LOAD_CONST 0 (None)
21 RETURN_VALUE
>>> dis.dis(g)
3 0 LOAD_GLOBAL 0 (a)
3 POP_JUMP_IF_FALSE 12
6 LOAD_CONST 1 (True)
9 JUMP_FORWARD 3 (to 15)
>> 12 LOAD_CONST 2 (False)
>> 15 STORE_FAST 0 (x)
18 LOAD_CONST 0 (None)
21 RETURN_VALUE
It is identical. Both functions "know" that a is a global name.
A name can refer to a global or a local name, not both. One consequence is
this error:
>>> a = 42
>>> def h():
... print(a)
... a = "foo"
...
>>> h()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in h
UnboundLocalError: local variable 'a' referenced before assignment
For class bodies there is an exception to allow for assignments of a global
to a local variable, e. g.:
>>> a = 42
>>> class A:
... print(a)
... a = "foo"
...
42
>>> A.a
'foo'
>>> a
42
More information about the Tutor
mailing list