I have code that looks like something like this:
def startSearching(self):
self.searchingLock.acquire()
searching = self.searching
if self.searching:
self.searchingLock.release()
self.logger.error("Already searching!")
return False
self.searching = True
self.searchingLock.release()
#some more init code, then start the thread which
#constantly checks self.searching to determine when to stop
it's kind of ugly, though. lots of acquires and releases. this looks prettier:
def startSearching(self):
with self.searchingLock:
if self.searching:
self.logger.error("Already searching!")
return False
self.searching = True
#some more init code, then start the thread which
#constantly checks self.searching to determine when to stop
but this keeps the lock longer than strictly necessary, espcially if self.logger.error
takes a while (like if it writes to disk, which it does). is there any middle ground between holding the lock as little as possible but having prettier code?
The best way to use a Lock is by using the with statement. It automatically handles the acquisition and release of lock, even if the block exits with an exception. It's impossible to substitute the with statement into your code without making a new minor modifications.
As discussed above, the lock is present inside python’s threading module. Also, it is used as a tool to synchronize threads. It has 2 different states In order to attain the locked state, we use the acquire () method.
Using these five tricks will help make your Python code more clean, readable, and elegant! Consider the following setup: we want to loop through each element in a 3 by 3 matrix, which is done with two for loops (one looping through each row, one looping through each column — element — in each row).
In the first line, import math, you import the code in the math module and make it available to use. In the second line, you access the pi variable within the math module. math is part of Python’s standard library, which means that it’s always available to import when you’re running Python. Note that you write math.pi and not just simply pi.
Maybe you need to separate this logic like:
def initSearch(self):
with self.searchingLock:
if self.searching : raise SearchingError('AlreadySearching')
self.searching = True
def startSearching(self):
try: self.initSearch()
except SearchingError as error :
self.logger.error(error.message)
return False
#some more init code, then start the thread which
#constantly checks self.searching to determine when to stop
And additionaly you telling your searchingLock
the reason to release it automaticaly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With