What does the keyword 'global' really mean

Peter Otten __peter__ at web.de
Tue Sep 9 08:28:30 EDT 2003


Michael Peuser wrote:

> (1) No! When you 'import' a modul all variables (except __...) will be
> visible to you.

As far as I know, there is no way to hide a module level variable:

<hidden.py>
x = "alpha"
_y = "beta"
__z = "gamma"
</hidden.py>

>>> import hidden
>>> dir(hidden)
['__builtins__', '__doc__', '__file__', '__name__', '__z', '_y', 'x']
>>>

> (2) You as well have visiblity inside a modul function to variables used
> in the modul scope, i.e. you do have to declare them 'global' if you only
> want to 'read' them.

Oops! You need not declare them when you do not want to bind them to another
object instance.

>> Also, does Python have the equivalent of the 'C' keyword 'static'?
> 
> Not as a special construct, but you can use real 'dummy keyword
> parameters' for that:
> 
> def p(p1,p2,....myown={}):
> myown[....] =
> 
> This trick will emulate something similar to 'static'

If you want to to emulate a "static" variable in a function, as in:

int contrived(void) { static int i=-1; i += 1; return i; }

use

def contrived():
    contrived.i += 1
    return contrived.i
contrived.i = -1

or (better, but will accept parameters only once)

def contrived():
    i = 0
    while True:
        yield i
        i += 1

or a class with a __call__() method
and live happily ever after.

Peter    




More information about the Python-list mailing list