Tim Golden wrote: > Dodging your question slightly (and at the risk of teaching > my grandmother to suck eggs) I sometimes use this idiom for > checking params. Obviously it only goes so far, but it's > fairly compact:
> <Noddy example code> > import os, sys > if __name__ == '__main__': > ARGS = None, "DEV" > filename, db = \ > (j or i for i, j in map (None, ARGS, sys.argv[1:])) > print sys.argv > print filename, db > </code> Thank you for the example. It demonstrates perfectly how much people miss this feature :) Raymond Hettinger wrote: > At first blush that example would make it seem like a good idea, but I > don't see how the example could extend past the first index. If the > port argument is optional, how would you know the index position of > optional arguments to follow? > With a dictionary, one could plausibly write: > host = d.get('host', 'http://example.com') > port = d.get('port', 8080) > path = d.get('path', '/') > But would this make sense with a list: > host = s.get(0, 'http://example.com') > port = d.get(1, 8080) > path = d.get(2, '/') > If positions 0 and 1 are optional, how do you expect to know whether > "path" is going to be at position 2? This problem doesn't exist with > dictionaries because the presence or absence of optional entries does > not affect the key reference to other entries. Accordingly, I > wouldn't expect that dict.get() would have a parallel list.get() with > plausible use cases. If you want to fill position 2, then positions 0 and 1 are mandatory. It is the simplest possible option parsing, I didn't said it was the most flexible :) But perhaps it was a wrong example altogether. Consider a couple more snippets, unrelated to command-line options. (found by searching 'IndexError' in the python standard library) this snippet from cmd.py: try: return self.completion_matches[state] except IndexError: return None transforms into return self.completion_matches.get(state) another one from fileinput.py try: line = self._buffer[self._bufindex] except IndexError: pass else: self._bufindex += 1 self._lineno += 1 self._filelineno += 1 return line line = self.readline() becomes line = self._buffer.get(self._bufindex) if line: self._bufindex += 1 self._lineno += 1 self._filelineno += 1 return line line = self.readline() both examples show reduction by 3 lines. There's nothing dictionary-specific in 'get', it is just a special use-case of '__getitem__' that is needed frequently. Since list has '__getitem__' it deserves to have 'get' too. -- http://mail.python.org/mailman/listinfo/python-list