Threads + Enviroment Variables

Jeff Shannon jeff at ccvcorp.com
Tue Oct 2 16:10:19 EDT 2001


Adonis Vargas wrote:

> im having problems accessing enviroment variables from within a thread; the
> error im am getting is an 'undefined' error, but the variables i definded
> but in a module-level.
> i.e.
>
> -- in module something.py --
> something = []
>
> -- in script --
> from something import * # import the variable 'something' right?
>
> def somefunction(somevalue):
>     return somevalue+=1

As someone else pointed out, this looks weird.  You probably want 'return
somevalue + 1' ...

>
> def somethreadedfunction():
>     for i in range(10):
>         something = somefunction(0) # boom. an 'undefined' error???
>         print something
>
> Thread(target=somethreadedfunction).start()

This looks like yet another example of why "from something import *" is almost
always a bad idea.  It's difficult to know what you're doing, even reading your
own code.  It would also help us if you had posted the exact text of the
'undefined' error you mention.

The big problem with what you're doing, is that "something = somefunction(0)"
does *not* modify the empty list you created in something.py -- it creates a
new, local variable of the same name, which obscures the global variable that
you created with your import * statement.  Your best solution for this would be
to not do the import * -- it's much safer to just 'import something', and then
'something.something = somefunction(0)' .

Note, however, that when you do this, you're throwing away the empty list you
created in something.py, so it's not apparent what you're hoping to accomplish.
This has nothing to do with threads, it's all about import, namespaces, and
object references.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list