thread variable scope with start_new_thread

Luxore alan.meadows at gmail.com
Fri Nov 11 00:30:33 CET 2005


Hello,

I am trying to create threaded python project and I'm running into some
weird Python variable scoping.

I am using the "thread" module (I know, it's old and I should be using
threading)... but for example:

<code>
import thread
def extract_archive(session, user, archive, dest=None):
    job_id = sunlib.job.new(...)
    def thread_extract_archive():
        if not os.path.exists(archive):
            <...do stuff...>
        if not os.path.isfile(archive):
            <...do stuff...>
        if dest == None:
            dest = os.path.dirname(archive)
        <...do more stuff...>
thread.start_new_thread(thread_extract_archive, ())
return job_id
</code>

It appears that thread_extract_archive() inherits many of the variables
that are passed or defined in extract_archive().   I find this scary,
although very convenient because my thread process needs to reference a
number of items.  The problem popped up when I added the "if dest ==
None" bit.  Python barks that "dest" is an uninitialized variable.
That would make sense to me, but what I find odd is that
thread_extract_archive() does not have any trouble accessing the
session, user, or archive variables.  The only difference is that I
pass these variables to other functions (e.g. os.path.isfile), and I am
doing a simple pythonic test on "dest."

What scares me is that my thread has access to extract_archive()
variables, but only if I access them in a certain way.

Any thoughts? Is there a way to use the more improved "threading"
module and pass my thread the entire variable scope of the parent
process like I am able to do above? 

Thanks,

Luxore.




More information about the Python-list mailing list