3 ms·
I don't think this works: def increment(key): value = None def do_incr(key): value = self.counter_table.get(key) if not
by cturner 18y ago
I don't think this works:
def increment(key):
value = None
def do_incr(key):
value = self.counter_table.get(key)
if not value:
self.counter_table.add(key, 1)
value = 1
with_lock(self.lock, do_incr, key)
Several reasons:
1) It refers to 'self' yet isn't a method.
2) In python you can't rebind variables outside of your scope. The change to value within do_incr won't work. You can operate on objects in the enclosing scope but you can't rebind them. This used to be a source of constant annoyance to me, but I've now got into the habit of just creating small objects in place for situations where I need to do that.
Also, this java example can be improved.
buf = StringBuffer()
buf.append("I don't recognize the command \"");
buf.append(s);
buf.append("Sorry.");
message = buf.toString();
The code certainly hasn't been tested - it's missing a 'new' and the resulting string has unbalanced quotes. Regardless - don't use StringBuffer unless you need the synchronization.
Do this instead:
StringBuilder buf = new StringBuilder(); {
buf.append("I don't recognize the command ");
buf.append('"').append(s).append('". ');
buf.append("Sorry.");
}
message = buf.toString();
This tactic of creating scopes to hide away detail while you build up objects works particularly well for situations where you're instantiating streams because your file input streams and the like can be hidden away in a mini scope and this makes it far less likely to run into a situation where you can't call a second file input stream 'fis' because you used that name higher in the method.
Also, it allows readers of your code to focus on the objects that are significant to the flow of code rather than the code used for building them up.
- eru 18y agoRegarding 1: You can refer to 'self' when you have bound it - it does not have to do anything with methods. Though 'self' is usually employed in methods.
- d0mine 18y agoAdditionaly, def increment(key): with lock(self.lock): value = self.counter_table.get(key) if not value: self.counter_table.add(key, 1) value = 1 Should be replace by: def increment(self, key): with lock(self.lock): value = self.counter_table[key] = self.counter_table.setdefault(key, 0) + 1 return value UserDict.DictMixin has setdefault method, therefore it is reasonable to assume that a dictionary-like object should have it.