Global Variables + Threads

Nick Perkins nperkins7 at home.com
Wed Jun 13 18:29:41 EDT 2001


>"Aahz Maruch" <aahz at panix.com> wrote:
>...
>Pass around a class instance.


If you pass a class instance to your Tkinter code, which contains the
information that you want to be 'global', then you can then modify the
information contained in that class from 'outside'.  If you simply pass in
the 'global' variables, then they will not stay 'connected' to the original
variables.

..passing a variable directly is like making a copy..
( actually, it makes another name which is bound to the
  same object, but if you modify the variable, it simply
  binds to another object, it does not actually change
  the object that it referred to ..(usually).  )

>>> class thing:
...  def __init__(self,x): self.x = x
...  def print_x(self): print self.x
...
>>> x = 'something'
>>> t = thing(x)
>>> t.print_x()
something
>>> x = 'something else'   # change value from 'outside'
>>> t.print_x()
something


...but if you pass in a reference to a class,
it will 'point to' the same object, and you can then
read or modify any 'parts' of that object, without
losing your reference to the original object.


>>> class globals: pass
...
>>> g=globals()
>>>
>>> class thing:
...  def __init__(self,globals): self.globals = globals
...  def print_x(self): print self.globals.x
...
>>> t = thing(g)
>>> g.x = 'something'
>>> t.print_x()
something
>>> g.x = 'something else'    # change value from 'outside'
>>> t.print_x()
something else


This has nothing to do with threads, it is just a matter of scoping and
binding.  Variables that are global are only really global to the module in
which they are defined.  Any other modules need to be explicity given access
to them.

Another option, I suppose, is have variables that you want to be
global...er, i mean, accessible from many scopes,... declared all in a
separate module, which can be imported by the other modules.

It all comes down to switching from thinking about 'variables and values',
to thinking about 'names and objects', and remembering that names can be
re-bound to different objects when you think that you are 'modifying a
variable'.

I'm not sure if this is exactly the original problem, but I had fun thinking
about it.






More information about the Python-list mailing list