Local variables and thread safety

dieter dieter at handshake.de
Sun Sep 20 08:02:34 CEST 2015


Saint Desmond <st.kooday at gmail.com> writes:

> Dear Team,
> Kindly advise if variables declared within a function are thread safe.

In general, yes. However, there are exceptions.

First of all, "variable" is not the optimal term to use in this context.
In Python, a "variable" is nothing more than the binding of a name
to an object. The local binding in a function itself is thread safe; however,
operations on the bound object may not be thread safe.

For example, if the bound object comes from outside the function
(i.e. it is visible outside the function) then other threads could
modify it and those modifications conflict with each other or
modifications in this thread.

Another example would be the use of a locally defined function
(wich can access "variable"s defined in the enclosing function) as
a thread.


Look at Python's "threading" module to find general purpose utilities
to assure thread safety.



More information about the Python-list mailing list