Created
July 10, 2014 07:19
-
-
Save kezabelle/8376477e038e23a589b0 to your computer and use it in GitHub Desktop.
Accessing `self.x` vs accessing a locally scoped equivalent?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MySharedObject(object): | |
""" | |
If using a locally scoped dictionary to check for duplicates, | |
do the same thread issues arise? | |
Note that I don't care about what gets stored -- it should be | |
the same end-result regardless of which threads do what, the | |
ValueError is mainly a developer-awareness issue. | |
""" | |
def do_stuff(self): | |
self.var = {} | |
seen = {} # the duplicate detector | |
iterable = self.collect_some_stuff() | |
for x in iterable: | |
if x in seen: | |
raise ValueError('Duplicate detected') | |
seen[x] = 1 | |
self.var[x] = 1 | |
self._built = True |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MySharedObject(object): | |
""" | |
If two threads hit do_stuff in tandem, ValueError may get raised | |
because the other thread may have already put `x` into `self.var` | |
""" | |
def do_stuff(self): | |
self._built = False | |
self.var = {} | |
iterable = self.collect_some_stuff() | |
for x in iterable: | |
if x in self.var: | |
raise ValueError('Duplicate detected') | |
self.var[x] = 1 | |
self._built = True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment