Python Tips
The “with” statement
This is just incredibly beautiful code.
Check out the source for more details on Python’s “with” statement if you’re interested.
Get current directory
Too useful not to know. Source is here.
max and min accept a sorting function
Instead of writing out this:
def best(candidates, scoref): '''Use scoref to find the candidate with the highest score.''' highest_score = float('-inf') best = None for candidate in candidates: candidate_score = scoref(candidate) if candidate_score > highest_score: highest_score = candidate_score best = candidate return best
You can just write:
max(iterable, key=scoref)
Don’t forget the “key” keyword, or Python will think you are comparing the list against the function. This is pretty cool because it makes things like getting the max value in a dictionary trivial.
>>> a = {'a': 1, 'b':2, 'c':3} >>> a {'a': 1, 'c': 3, 'b': 2} >>> max(a, key=lambda x: a[x]) 'c'
Comment