How to define a GLOBAL Variable ?

François Pinard pinard at iro.umontreal.ca
Thu Aug 2 10:56:19 EDT 2001


[François Pinard]

> [Peter Moscatt]

> > If I wish to define a variable that I want to become global to ALL classes
> > within a .py file - how is this best achieved ?

> Hell, Peter.

Grrumph!  What a typo!  I meant "Hello", of course! :-)

> It's easy (like most things in Python!).  Just define your class global
> variable, using the class name to the left of a dot.  For example:

>         >>> class Factory:
>         ...	def printer(self):
>         ...		print self.value
>         ... 
>         >>> a = Factory()
>         >>> b = Factory()
>         >>> Factory.value = 3.1415926
>         >>> a.printer()
>         3.1415926
>         >>> b.printer()
>         3.1415926

I might have misread your request, while reading my answer.  I understood
that you wanted to define a variable to become global to all instances of
a given class, and this is to what the above replies.  Sorry!

If you want to define a global variable in a module, just do it at the other
level, that is, outside any "def ...:".  You do not have to textually define
it before referring to it, as long as the global assignment dynamically
occurs before the references to it.  If you want to define a global within a
"def ...:", use the "global" declaration, like this:

    def some_function:
        global value
        value = 3.1415926

and just refer to `value' from anywhere else, afterwards.

If you request is really to define a global variable in all classes,
but not outside them, this might become a bit more tricky.  Presuming that all
your classes are defined at the outer level of your module, you might do:

    import types
    for klass in globals().values():
        if type(klass) is types.ClassType:
            klass.value = 3.1415926

and then refer to "self.value" into any class method.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard




More information about the Python-list mailing list