On Tue, 28 Feb 2017 at 17:19 David Mertz <me...@gnosis.cx> wrote:

> On Tue, Feb 28, 2017 at 7:16 AM, Michel Desmoulin <
> desmoulinmic...@gmail.com> wrote:
>
> Le 28/02/2017 à 15:45, Steven D'Aprano a écrit :
> > No you don't. You can use slicing.
> > alist = [1, 2, 3]
> > print(alist[99:100])  # get the item at position 99
>
> No this gives you a list of one item or an empty list.
>
> dict.get('key', default_value) let you get a SCALAR value, OR a default
> value if it doesn't exist.
>
>
>     x = (alist[pos:pos+1] or [default_val])[0]
>
>
> How so ? "get the element x or a default value if it doesn't exist" seem
> at the contrary, a very robust approach.
>
>
> Yes, and easily written as above.  What significant advantage would it
> have to spell the above as:
>

I think code like that is convoluted and confusing and I'm surprised to see
anyone at all advocating it.

IMO, the sane thing to compare this with is a conditional expression. There
aren't any spellings of that that aren't ugly either:

>>> stuff[x] if len(stuff) > x else default
>>> stuff[x] if stuff[x:x+1] else default

As for a reasonable use of list.get (or tuple.get), I often end up with
lists of arguments and would like to take values from the list if they
exist or take a default if not. This looks particularly horrible if the
index isn't a variable (so most of the time):

    something = args[1] if len(args) > 1 else "cheese"
    something_else = args[2] if len(args) > 2 else "eggs"

(you could make it more horrible by using the slicing trick, but I don't
see much point in demonstrating that.)

I don't often want to use dicts and lists in the same code in this way, but
I think the crucial point about the comparison with dicts is that code like
this is simpler and clearer if you do something horrible like this, just to
get .get():

>>> argdict = dict(enumerate(args))

Ed

P.S. all the talk of PEP 463 seems misplaced. That it solves (FSVO solve)
this problem doesn't mean it should supersede this discussion. Personally,
I don't think I'd use except-expressions, but I would use list.get.
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to