thread variable scope with start_new_thread
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
> I am using the "thread" module (I know, it's old and I should be using
> threading)... but for example:
> 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
> 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:
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
for more on nested scopes, read the above page carefully, and, if
you want even more details, this page:
More information about the Python-list