Skip to content

Commit 0b7b80b

Browse files
committed
Document the convert() with initialization pattern, closes #420
1 parent 396f80f commit 0b7b80b

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

docs/cli.rst

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1002,6 +1002,8 @@ The ``--convert`` option also works with the ``--csv``, ``--tsv`` and ``--nl`` i
10021002

10031003
As with ``sqlite-utils convert`` you can use ``--import`` to import additional Python modules, see :ref:`cli_convert_import` for details.
10041004

1005+
You can also pass code that runs some initialization steps and defines a ``convert(value)`` function, see :ref:`cli_convert_complex`.
1006+
10051007
.. _cli_insert_convert_lines:
10061008

10071009
\-\-convert with \-\-lines
@@ -1285,6 +1287,27 @@ This supports nested imports as well, for example to use `ElementTree <https://d
12851287
'xml.etree.ElementTree.fromstring(value).attrib["title"]' \
12861288
--import=xml.etree.ElementTree
12871289

1290+
.. _cli_convert_complex:
1291+
1292+
Using a convert() function to execute initialization
1293+
----------------------------------------------------
1294+
1295+
In some cases you may need to execute one-off initialization code at the start of the run. You can do that by providing code that runs before defining your ``convert(value)`` function.
1296+
1297+
The following example adds a new ``score`` column, then updates it to list a random number - after first seeding the random number generator to ensure that multiple runs produce the same results::
1298+
1299+
$ sqlite-utils add-column content.db articles score float --not-null-default 1.0
1300+
$ sqlite-utils convert content.db articles score '
1301+
import random
1302+
random.seed(10)
1303+
1304+
def convert(value):
1305+
global random
1306+
return random.random()
1307+
'
1308+
1309+
Note the ``global random`` line here. Due to the way the tool compiles Python code, this is necessary to ensure the ``random`` module is available within the ``convert()`` function. If you were to omit this you would see a ``NameError: name 'random' is not defined`` error.
1310+
12881311
.. _cli_convert_recipes:
12891312

12901313
sqlite-utils convert recipes

0 commit comments

Comments
 (0)