What does the keyword 'global' really mean

Michael Peuser mpeuser at web.de
Tue Sep 9 15:43:14 CEST 2003


"Peter Otten" <__peter__ at web.de
> 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:

Funny, so it seems....

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

> Oops!
Oops as well! But this typo should be evident from the context...

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

This has the drawback that 'i' is not so well encapsulated (initialisation
outside) and - thus -visible outside of contrived. But it is certainly
somwhat  simpler.

Kindly
Michael P









More information about the Python-list mailing list