D
Denis Bilenko
Why does list have no 'get' method with exactly the same semantics as
dict's get,
that is "return an element if there is one, but do NOT raise
an exception if there is not.":
def get(self, item, default = None):
try:
return self[item]
except IndexError:
return default
It is often desirable, for example, when one uses the easiest
command-line options parsing - based on absolute positions:
With such a method instead of this (snippet from BaseHTTPServer.py)
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 8000
we could write
port = sys.argv.get(1) or 8000
which is both more condense and more clear.
The change is unlikely to break anyone's code.
(nobody uses getattr(obj, 'get') to distinguish between lists and dicts, right?)
dict's get,
that is "return an element if there is one, but do NOT raise
an exception if there is not.":
def get(self, item, default = None):
try:
return self[item]
except IndexError:
return default
It is often desirable, for example, when one uses the easiest
command-line options parsing - based on absolute positions:
With such a method instead of this (snippet from BaseHTTPServer.py)
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 8000
we could write
port = sys.argv.get(1) or 8000
which is both more condense and more clear.
The change is unlikely to break anyone's code.
(nobody uses getattr(obj, 'get') to distinguish between lists and dicts, right?)