You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Safely navigate through unsafe data: dicts, tuples, lists, strings and objects
5
4
6
-
Inspired on Ruby's [dig](https://www.rubydoc.info/stdlib/core/Hash:dig).
5
+
Safely navigate through unsafe data structures: dictionaries, tuples, lists, strings, and even custom objects.
7
6
8
-
```
7
+
Inspired by Ruby’s [`dig`](https://www.rubydoc.info/stdlib/core/Hash:dig).
8
+
9
+
```bash
9
10
pip install py-data-digger
10
11
```
11
12
12
-
## Why?
13
-
### TLDR:
14
-
Sometimes you don't want to deal with Python exceptions when accessing lists and dicts. If the data you need isn't there, you just want to **move on**...
13
+
---
15
14
16
-
**No ifs, no try-excepts!**
15
+
## 💡 Why?
16
+
### TL;DR:
17
+
Sometimes, you just don’t want to deal with Python exceptions when accessing nested lists and dictionaries.
18
+
If the data isn’t there, you just want to **move on** — no `if`s, no `try`-`except`s!
This is unsafe because it is highly prone to raise `IndexError`, `KeyError`, `TypeError` if you use the wrong key/index or if the data just isn't there.
61
+
This can raise `KeyError`, `IndexError`, or `TypeError` if any part of the structure is missing or malformed.
62
+
63
+
---
64
+
65
+
### 😴 The safe (but verbose) way:
53
66
54
-
### 😴 The safe (but boring) strategy:
55
67
```python
56
-
machines: list|None= nasty_dict.get("machines")
57
-
machine: dict|None=next(iter(machines), None) if machines elseNone
58
-
engine: dict|None= machine.get("engine") if machine isnotNoneelseNone
59
-
components: list|None: engine.get("components") if engine isnotNoneelseNone
60
-
68
+
machines = nasty_dict.get("machines")
69
+
machine =next(iter(machines), None) if machines elseNone
70
+
engine = machine.get("engine") if machine elseNone
71
+
components = engine.get("components") if engine elseNone
61
72
```
62
73
63
-
This is not only tedious but labourious!
64
-
At least, it's safe. We would not raise errors to break our code.
74
+
Safe, yes — but tedious and hard to read.
65
75
76
+
---
66
77
67
-
## Introducing `dig`
68
-
With this tool we may quickly and securely navigate through all sorts of nested data.
78
+
## ✅ Enter `dig()`
79
+
80
+
With `dig()`, you can safely access deeply nested data in a concise and readable way:
69
81
70
-
Let's consider the `nasty_dict` from the past section and that we also want to access the list of components.
0 commit comments