On Apr 7, 5:06 pm, Kiuhnm <kiuhnm03.4t.yahoo.it> wrote: > On 4/7/2012 22:09, Bryan wrote:>> For instance, let's say I want to make this > code thread-safe: > > >> ---> > >> myDict = {} > > >> def f(name, val): > >> if name not in myDict: > >> myDict[name] = val > >> return myDict[name] > >> <--- > > > First, don't re-code Python's built-ins. The example is a job for > > dict.setdefault(). > > [...] > > That was just an example for the sake of the discussion. > My question is this: can I use 'threading' without interfering with the > program which will import my module?
'import threading' ought to work everywhere, but that's not enough to tell you whether whatever you're trying to do will actually work. However, you shouldn't need to do it unless your application is meant to /only/ be used in applications that have done 'import threading' elsewhere. Otherwise, you probably have a pretty serious design issue. Global state is bad. TLS state is little better, even if it's common in a lot of python modules. Non-thread-safe object instances is usually fine. Object construction needs to be thread-safe, but that's also the default behavior. You need not worry about it unless you're doing very unusual things. Plainly, most of the time you shouldn't need to do anything to support multiples threads beyond avoiding global state. In fact, you should stop and give some serious thought to your design if you need to do anything else. Adam -- http://mail.python.org/mailman/listinfo/python-list