thread variable scope with start_new_thread

Fredrik Lundh fredrik at pythonware.com
Fri Nov 11 00:49:35 CET 2005


"Luxore" <alan.meadows at gmail.com> wrote:

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

the "weird scoping" you're seeing has nothing to do with threads
(read on)

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

no, the difference is that you're assigning to "dest" in the inner function.
anything you assign to is considered to be a local variable:

    http://docs.python.org/ref/naming.html

    If a name is bound in a block, it is a local variable of that block.
    If a name is bound at the module level, it is a global variable. /.../
    If a variable is used in a code block but not defined there, it is a
    free variable.

for more on nested scopes, read the above page carefully, and, if
you want even more details, this page:

    http://www.python.org/peps/pep-0227.html

</F>






More information about the Python-list mailing list