|
| 1 | +.. hide: |
| 2 | +
|
| 3 | + >>> from inform import Inform |
| 4 | + >>> ignore = Inform(prog_name=False) |
| 5 | +
|
| 6 | +
|
1 | 7 | ***************
|
2 | 8 | Common mistakes
|
3 | 9 | ***************
|
4 | 10 |
|
5 | 11 | .. currentmodule:: nestedtext
|
6 | 12 |
|
| 13 | +Two Values for One Key |
| 14 | +---------------------- |
| 15 | + |
7 | 16 | When :func:`load()` or :func:`loads()` complains of errors it is important to
|
8 | 17 | look both at the line fingered by the error message and the one above it. The
|
9 | 18 | line that is the target of the error message might by an otherwise valid
|
@@ -80,3 +89,55 @@ trailing whitespace. To do so in Vim, add::
|
80 | 89 | set listchars=trail:␣
|
81 | 90 |
|
82 | 91 | to your ~/.vimrc file.
|
| 92 | + |
| 93 | + |
| 94 | +Lists or Strings at the Top Level |
| 95 | +--------------------------------- |
| 96 | + |
| 97 | +Most *NestedText* files start with key-value pairs at the top-level and we |
| 98 | +noticed that many developers would simply assume this in their code, which would |
| 99 | +result in unexpected crashes when their programs read legal *NestedText* files |
| 100 | +that had either a list or a string at the top level. To avoid this, the |
| 101 | +:func:`load` and :func:`loads` functions are configured to expect a dictionary |
| 102 | +at the top level by default, which results in an error being reported if |
| 103 | +a dictionary key is not the first token found: |
| 104 | + |
| 105 | +.. code-block:: python |
| 106 | +
|
| 107 | + >>> import nestedtext as nt |
| 108 | +
|
| 109 | + >>> content = """ |
| 110 | + ... - a |
| 111 | + ... - b |
| 112 | + ... """ |
| 113 | +
|
| 114 | + >>> try: |
| 115 | + ... print(nt.loads(content)) |
| 116 | + ... except nt.NestedTextError as e: |
| 117 | + ... e.report() |
| 118 | + error: 2: content must start with key or brace ({). |
| 119 | + 2 ❬- a❭ |
| 120 | +
|
| 121 | +This restriction is easily removed using *top*: |
| 122 | +
|
| 123 | +.. code-block:: python |
| 124 | +
|
| 125 | + >>> try: |
| 126 | + ... print(nt.loads(content, top=list)) |
| 127 | + ... except nt.NestedTextError as e: |
| 128 | + ... e.report() |
| 129 | + ['a', 'b'] |
| 130 | +
|
| 131 | +The *top* argument can take any of the following values: *"dict"*, *dict*, |
| 132 | +*"list"*, *list*, *"str"*, *str*, *"any"*, or *any*. The default value is |
| 133 | +*dict*. The value given for *top* also determines the value returned by |
| 134 | +:func:`load` and :func:`loads` if the *NestedText* document is empty. |
| 135 | +
|
| 136 | +================ ================================= |
| 137 | +*top* value returned for empty document |
| 138 | +---------------- --------------------------------- |
| 139 | +*"dict"*, *dict* ``{}`` |
| 140 | +*"list"*, *list* ``[]`` |
| 141 | +*"str"*, *str* ``""`` |
| 142 | +*"any"*, *any* *None* |
| 143 | +================ ================================= |
0 commit comments