On 2020-06-27 09:34, Daniel. wrote:
When I need to traverse nested dicts, is a common pattern to do

somedict.get('foo', {}).get('bar', {})

But there is no such equivalent for arrays, wouldn't be nice if we can follow

somedict.get('foo', {}).get('bar', []).get(10) ... ?

What do you think?


I would use this. I do something similar already, albeit as a set of classes that wrap around Python `dict` and `list` to provide the null-safe access.

to_data(somedict).foo.bar[10]

Specifically, I wrap `list` in `FlatList`, which will return `Null` (null-safe version of `None`) instead of raising and IndexError.  This allows math on indexes without concern for corner cases, and makes window functions easier to write:

|    my_list = FlatList(my_list)
|    deltas = []
|    for i, this_week in enumerate(my_list):
|        last_week = my_list[i-7]
|        deltas.append(this_week - last_week)

by avoiding exception handling, code is simplified, and procedures simplify to functions.  Instead of code that constructs a list; the code reads as a list definition:

|    deltas = [
|        this_week - last_week
|        for my_list in [FlatList(my_list)]
|        for i, this_week in enumerate(my_list)
|        for last_week in [my_list[i-7]]
|    ]

> please forgive me:  where `for x in [y]` can be read as `x=y`  (I am still hesitant to use `:=`)

There are detriments to using a set of null-safe objects:

1. data structures can be polluted with a combination of null-safe objects and regular Python structures

2. with null-safe code, there are more nulls and it seems EVERYTHING must be null-safe, including arithmetic (notice null-safe subtraction above)

3. runs slower; all the null-safe checks dominate my profiler time.


I would be nice if Python had a series of null-safe operators. Until then, `list.get` would eliminate my extra object creation:

|    deltas = [
|        this_week - (last_week or 0)
|        for i, this_week in enumerate(my_list)
|        for last_week in [my_list.get(i-7)]
|    ]

Although we see additional null-checks required (as #2 states).

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/UKU2PN43EQZ4ZWVDFXR6XO4ST3WBCNVE/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to