Debian Codegraph @

doc/tutorial-1.rst

raw
1 .. meta::
2 :description: pydoit tutorial - walkthrough doit basic and intermediate concepts with real-world example
3 :keywords: python, doit, tutorial, getting started, graph, graphviz, task-runner, pipeline
4
5 .. title:: pydoit tutorial - build a graph of module's imports
6
7
8 ======================================
9 tutorial - python imports graph
10 ======================================
11
12 This tutorial demonstrates how to use ``doit`` to create a simple computational pipeline.
13
14 The goal is to create a graph of python module's imports in a package.
15 `graphviz <http://graphviz.org/>`_'s **dot** tool will be used to generate the graph.
16
17 As an example, the `requests <https://github.com/requests/requests>`_ package will be used. The result is the image below:
18
19 .. image:: _static/requests.png
20
21
22 In the image an arrow represents an import from one module to another. For example in the left side of image you can see an arrow from `requests.status_codes` to `requests.structures`. This comes from the following line in `status_code.py`:
23
24 .. code-block:: python3
25 :caption: requests/status_codes.py
26
27 from .structures import LookupDict
28
29
30 Drawing an "import" dependency graph can be very useful in understanding how the code in a package is organized.
31 It may also help you identify potential problems like circular imports.
32
33 There are three main steps to generate this graph:
34
35 1) read each python module and list its imports
36 2) generate a `dot` (text format) file representing the graph
37 3) generate an image (PNG) from the `dot` file
38
39
40 setup
41 =====
42
43 required python packages
44 ------------------------
45
46 .. code-block:: console
47
48 $ pip install doit pygraphviz import_deps
49
50 Note that on some linux systems it is necessary to install the system package `graphviz-dev` first.
51
52 sample project
53 --------------
54
55 First create a directory that will contain the projects to be analyzed.
56
57 .. code-block:: console
58
59 $ mkdir projects
60
61 Then clone the ``requests`` project
62
63 .. code-block:: console
64
65 $ cd projects
66 $ git clone [email protected]:requests/requests.git
67 $ cd ..
68
69
70
71 finding a module's import
72 =========================
73
74 Using `import_deps <https://github.com/schettino72/import-deps>`_ list all (intra-packages) imports from a module:
75
76 For example:
77
78 .. code-block:: console
79
80 $ python -m import_deps projects/requests/requests/models.py
81 requests._internal_utils
82 requests.auth
83 requests.compat
84 requests.cookies
85 requests.exceptions
86 requests.hooks
87 requests.status_codes
88 requests.structures
89 requests.utils
90
91
92 The output contains one imported module per line.
93
94
95 doit task
96 ---------
97
98 On the next step we are going to wrap the above script in a ``doit`` *task*.
99 In ``doit`` tasks are defined in a plain python module, by default called ``dodo.py``.
100
101 For example, a trivial task to execute the script above and save its output into a file would be:
102
103
104 .. code-block:: python3
105 :caption: dodo.py
106
107 def task_imports():
108 return {
109 'actions': ['python -m import_deps '
110 'projects/requests/requests/models.py > requests.models.deps'],
111 }
112
113
114 In this module you write functions that are **task-creators**,
115 the role of which is not to execute tasks but to return tasks' metadata.
116 **task-creators** are any function whose name starts with ``task_``.
117 A task name is taken from the function name, so
118 in this case the task is called ``imports``.
119
120 The most important *Task* metadata is ``actions``, which defines what will be done when a task is executed.
121
122 Note that ``actions`` is a list where its element are strings to be interpreted as shell commands.
123
124
125 task execution
126 --------------
127
128 ``doit`` comes with a command line tool to act upon the set of tasks defined in a specific file. The default file is ``dodo.py`` in the current directory. With no argument it executes all tasks found in it.
129
130 .. code-block:: console
131
132 $ doit
133 . imports
134
135
136 The output reports that the ``imports`` task was executed.
137 You can check that a file ``requests.models.deps`` was created with
138 a list of modules imported by ``requests.models``.
139
140
141 incremental computation
142 -----------------------
143
144 One of the main purposes of ``doit`` is to make use
145 of **up-to-date** checks to decide if tasks *need* to be executed or not.
146
147 In our case, as long as the input file is not modified we are certain
148 that the same output would be generated...
149
150 When dealing with files, task's metadata ``file_dep`` and ``targets`` can be used:
151
152
153 .. task_imports, line 11 is clean
154 .. literalinclude:: tutorial/tuto_1_1.py
155 :language: python3
156 :lines: 5-10,12
157
158
159 Note how ``actions`` can make use of variable substitution for
160 ``%(dependencies)s`` and ``%(targets)s``.
161
162 Now let's execute it again:
163
164 .. code-block:: console
165
166 $ doit
167 . imports
168
169 And then, a second time:
170
171 .. code-block:: console
172
173 $ doit
174 -- imports
175
176
177 Note that the second time there is a ``--`` instead of ``.`` preceding the task name.
178 This means that the task was not executed, ``doit`` understood that
179 the task output would be the same as previously generated,
180 so it does not execute the task again.
181
182 .. warning::
183
184 When ``doit`` *loads* a ``dodo.py`` file it executes all *task-creator* functions in order to generate all tasks metadata.
185 A task's ``action`` is only executed if the task is selected to run and not **up-to-date**.
186
187 Expensive computation should always be done on task's ``action``
188 and never on the body of a **task-creator** function.
189
190
191 rules for up-to-date checks on files
192 ------------------------------------
193
194
195 file_dep
196 ^^^^^^^^
197
198 ``doit`` uses the *md5* of ``file_dep`` to determine if a dependency has changed.
199
200
201 .. code-block:: console
202
203 $ touch projects/requests/requests/models.py
204 $ doit
205 -- imports
206 $ echo "# comment" >> projects/requests/requests/models.py
207 $ doit
208 . imports
209
210
211 Note that simply changing a file timestamp does not trigger a new execution.
212
213
214 targets
215 ^^^^^^^
216
217 For ``targets``, the only verification that is made is whether the file exists or not.
218 So if a target is removed it will be re-created even if the dependencies remain unmodified.
219
220 .. code-block:: console
221
222 $ rm requests.models.deps
223 $ doit
224 . imports
225
226
227
228 graphviz dot
229 ============
230
231
232 On the next step we will create a `graphviz <http://graphviz.org/>`_'s ``dot`` file.
233 ``dot`` is a language to describe graphs.
234
235 The code below defines a python function to read a file containing
236 import dependencies (as generated by our previously defined ``imports`` task).
237
238
239 .. module_to_dot()
240 .. literalinclude:: tutorial/tuto_1_1.py
241 :language: python3
242 :lines: 1-3,14-15,18-27
243
244
245 Task with python action
246 -----------------------
247
248 Next we define the ``dot`` task, which is similar to previous tasks...
249 except for the fact that instead of passing a string with a shell command
250 we directly pass the previously created python function ``module_to_dot``.
251
252
253
254 .. task_dot()
255 .. literalinclude:: tutorial/tuto_1_1.py
256 :language: python3
257 :lines: 28-33,35
258
259
260 Also note that the function takes the special parameters ``dependencies`` and ``targets``, whose values will be injected by ``doit`` in the function call.
261
262
263 .. code-block:: console
264
265 $ doit
266 -- imports
267 . dot
268
269
270 To indicate a failure, a python-action should return the value ``False`` or raise an exception.
271
272
273
274 graph image
275 -----------
276
277 Finally lets add another task to generate an image from the `dot` file using the graphviz command line tool.
278
279
280 .. task_draw()
281 .. literalinclude:: tutorial/tuto_1_1.py
282 :language: python3
283 :lines: 38-43,45
284
285
286
287 .. code-block:: console
288
289 $ doit
290 -- imports
291 -- dot
292 . draw
293
294
295 Opening the file ``requests.models.png`` you should get the image below:
296
297 .. image:: _static/requests.models.png
298
299
300
301 doit command line
302 =================
303
304
305 ``doit`` has a rich (and extensible) command line tool to manipulate your tasks. So far we have only executed ``doit`` without any parameters...
306
307 ``doit`` command line takes the form of ``doit <sub-command> <options> <arguments>``,
308 where ``options`` and ``arguments`` are specific to the ``sub-command``.
309
310 If no sub-command is specified the default command ``run`` is used.
311 ``run`` executes tasks...
312
313
314 doit help
315 ---------
316
317 ``doit help`` will list all available sub-commands.
318
319 You can get help for a specific sub-command with ``doit help <sub-command>``, i.e. ``doit help run``.
320
321 You can also get help for the task metadata fields with ``doit help task``.
322
323
324 doit list
325 ---------
326
327 The command ``list`` displays the list of known tasks:
328
329 .. code-block:: console
330
331 $ doit list
332 dot generate a graphviz's dot graph from module imports
333 draw generate image from a dot file
334 imports find imports from a python module
335
336
337 Note how the docstring from *task-creators* functions were used as tasks' description.
338
339
340 info
341 ----
342
343 The ``info`` command can be used to get more information about a specific task's
344 metadata and state (whether it is up-to-date or not).
345
346
347 .. code-block:: console
348
349 $ doit info imports
350
351 imports
352
353 find imports from a python module
354
355 status : up-to-date
356
357 file_dep :
358 - projects/requests/requests/models.py
359
360 targets :
361 - requests.models.deps
362
363
364 run
365 ---
366
367 ``run`` is the default command, and usually not explicitly typed.
368 So ``$ doit`` and ``$ doit run`` do exactly the same thing.
369
370 Without any parameters ``run`` will execute all of your tasks.
371 You can also select which tasks to be executed by passing a sequence of tasks' names.
372
373 For example if you want to execute only the ``imports`` task you would type:
374
375
376 .. code-block:: console
377
378 $ doit imports
379 -- imports
380
381
382 Note that even if you explicitly pass the name of the task to be executed,
383 ``doit`` will actually execute the task only if it is not **up-to-date**.
384
385 You can also pass more than one task:
386
387 .. code-block:: console
388
389 $ doit imports dot
390 -- imports
391 -- dot
392
393
394 Another important point to take notice of is that even
395 if you specify only one task, ``doit`` will run all of the dependencies of the specified task.
396
397 .. code-block:: console
398
399 $ doit dot
400 -- imports
401 -- dot
402
403
404 Note how the ``imports`` task was run because task ``dot`` has ``file_dep`` that is a target of ``imports`` task.
405
406
407 clean
408 -----
409
410 A common use-case is to be able to "revert" the operations done by a task.
411 ``doit`` provides the ``clean`` command for that.
412
413 By default it does nothing... You need to add the parameter ``clean`` to the task's metadata. For the most common case where you just want to remove the created targets, just pass the value ``True``.
414
415 You can also write custom ``actions`` (shell or python) to specify what should be done as a value to ``clean`` field.
416
417 Add ``clean`` to all defined tasks, like:
418
419 .. task_draw()
420 .. literalinclude:: tutorial/tuto_1_1.py
421 :language: python3
422 :lines: 38-45
423 :emphasize-lines: 7
424
425
426 Executing ``clean``:
427
428 .. code-block:: console
429
430 $ doit clean
431 draw - removing file 'requests.models.png'
432 dot - removing file 'requests.models.dot'
433 imports - removing file 'requests.models.deps'
434
435
436 Since targets were removed this will force the tasks to be executed on next ``run``.
437
438 .. code-block:: console
439
440 $ doit
441 . imports
442 . dot
443 . draw
444
445
446
447 forget
448 ------
449
450 ``doit`` will look for changes in the dependencies, but not for changes in the code that defines the tasks...
451 While developing a task, it is common to want to force its execution after making changes to it.
452
453 For example, let's change the colors of the nodes in the graph:
454
455 .. module_to_dot()
456 .. literalinclude:: tutorial/tuto_1_1.py
457 :language: python3
458 :lines: 14-21
459 :emphasize-lines: 3-4
460
461
462 To force its execution we need ``doit`` to ``forget`` its state thus so:
463
464 .. code-block:: console
465
466 $ doit forget dot
467 forgetting dot
468
469 .. code-block:: console
470
471 $ doit
472 -- imports
473 . dot
474 . draw
475
476
477 .. image:: _static/requests.models-blue.png
478
479
480 .. note::
481
482 Another option to force the execution of a task after code changes is to use `run``'s command option ``-a/--always-execute``. That will ignore the **up-to-date** check and always execute tasks.
483
484
485 Code :download:`dodo.py <tutorial/tuto_1_1.py>`.
486
487
488 Pipelines
489 =========
490
491 So far we have built a traditional "file" based pipeline where one task's target is used as a dependency for another task.
492
493 While ``doit`` provides first-class support for file based pipelines, they are not required.
494
495 get module imports - python
496 ---------------------------
497
498 Let's rewrite the ``imports`` task to use a python action instead of a shell command:
499
500 .. task_imports()
501 .. literalinclude:: tutorial/tuto_1_2.py
502 :language: python3
503 :lines: 4-19
504 :emphasize-lines: 8,15
505
506
507
508 The function ``get_imports`` is used as the task's action.
509 It returns a dictionary, which will be saved by ``doit`` in its internal database. The returned dictionary must contain only values that can be encoded as JSON.
510
511 ``get_imports`` takes the path's module as a parameter (``module_path``). The value that will be used for this parameter upon task execution is specified in the ``actions`` of the task definition. Generally speaking, each element of the ``actions`` array is a tuple *(callable, args, kwargs)*.
512
513 .. note::
514
515 Note in this example for simplicity we are using ``doit`` internal database, but it is also possible to use any other external database or data source.
516
517
518
519 getargs
520 -------
521
522 The task's parameter ``getargs`` can be used to extract values from another task's result and pass it as a parameter to the current task's action.
523 It's a dictionary of the form
524
525 .. code-block:: python
526
527 {target_key: (task_name, source_key)}
528
529 and what it does is to execute the task ``task_name``, get the value of ``source_key`` from its resulting dict, and passing that as the argument named ``target_key`` of the current task's action.
530
531
532
533 .. task_dot()
534 .. literalinclude:: tutorial/tuto_1_2.py
535 :language: python3
536 :lines: 22-38
537 :emphasize-lines: 1,14,15
538
539
540 Note how ``module_to_dot`` takes 3 parameters:
541
542 - ``source``: value is passed directly when the task's actions is defined
543 - ``sinks``: value is taken from ``imports`` task's result
544 - ``targets``: values is taken from Task metadata
545
546
547 Everything should work as before, but without the creation of intermediate files.
548
549 ``doit`` can determine if the task ``imports`` is **up-to-date** even without a target file (it will just look at the ``file_dep``).
550
551 ``doit`` can also determine if ``dot`` is **up-to-date** by comparing the value returned by ``imports`` (its dependency through the ``getargs`` parameter), with the value stored in its database.
552
553 Code :download:`dodo.py <tutorial/tuto_1_2.py>`.
554
555
556 package imports
557 ===============
558
559 So far we have been creating a graph of a single module.
560 Let's process all modules in the package.
561
562 ``doit`` has the concept of a **task-group**.
563 A task group performs the same operation over a set of instances.
564 To create a task group the task-creator function should ``yield`` one or more task dictionaries with task metadata.
565
566 Note that each task is still independent.
567 Since each task needs to be independently identified an extra parameter ``name`` must be provided.
568
569
570 .. task_imports()
571 .. literalinclude:: tutorial/tuto_1_3.py
572 :language: python3
573 :lines: 8-22
574 :emphasize-lines: 4,11,12
575
576
577 Sub-tasks (items of task group) by default are not reported by the ``list`` command. They can be displayed, though, using the ``--all`` flag.
578
579 .. code-block:: console
580
581 $ doit list
582 dot generate a graphviz's dot graph from module imports
583 draw generate image from a dot file
584 imports find imports from a python module
585
586 .. code-block:: console
587
588 $ doit list --all imports
589 imports find imports from a python module
590 imports:requests.__init__
591 imports:requests.__version__
592 imports:requests._internal_utils
593 imports:requests.adapters
594 imports:requests.api
595 imports:requests.auth
596 imports:requests.certs
597 imports:requests.compat
598 imports:requests.cookies
599 imports:requests.exceptions
600 imports:requests.help
601 imports:requests.hooks
602 imports:requests.models
603 imports:requests.packages
604 imports:requests.sessions
605 imports:requests.status_codes
606 imports:requests.structures
607 imports:requests.utils
608
609
610 Note the task's name is composed of the task's group name (aka ``basename``)
611 followed by a colon `:` and the ``name`` specified as a parameter when ``yield``.
612
613 From the command line, a single task can be executed like this::
614
615 $ doit imports:requests.models
616 . imports:requests.models
617
618
619 getargs from group-task
620 -----------------------
621
622 ``getargs`` can also be used to get values from a *group-task*.
623 The difference is that its value will be a dictionary where the
624 key is the sub-task name:
625
626
627 .. task_dot()
628 .. literalinclude:: tutorial/tuto_1_3.py
629 :language: python3
630 :lines: 25-41
631 :emphasize-lines: 5,13-15
632
633
634 Finally, adjust task ``draw``.
635
636 .. task_draw()
637 .. literalinclude:: tutorial/tuto_1_3.py
638 :language: python3
639 :lines: 44-51
640 :emphasize-lines: 4-5
641
642
643 Running ``doit`` you should get the file ``requests.png`` with the image below:
644
645 .. image:: _static/requests.png
646
647
648 Code :download:`dodo.py <tutorial/tuto_1_3.py>`.
649
650
651 printing imports
652 ================
653
654 Getting rid of intermediate computation files (like ``requests.models.deps``) was nice...
655 but sometimes it is useful to be able to quickly list the direct imports from a module.
656
657 Let's create another task that just prints its output in the terminal.
658
659 .. task_print()
660 .. literalinclude:: tutorial/tuto_1_4.py
661 :language: python3
662 :lines: 12-14, 32-44
663 :emphasize-lines: 14-15
664
665 Here again we used a **task-group** to create one task per python module and ``getargs`` to extract the list of modules' imports from ``imports``'s result.
666
667 Also note the usage of two metadata fields not seen before: ``uptodate`` and ``verbosity``.
668
669
670 custom `uptodate`
671 -----------------
672
673 So far we have seen how ``doit`` can determine if a task is **up-to-date** by taking into consideration changes to ``file_dep``, if ``targets`` exist and results from ``getargs`` have changed.
674
675 While those cover a wide range of use cases, ``doit`` also provides a way to specify completely custom checks for **up-to-date**, using the ``uptodate`` field.
676
677 In this case the ``print`` task actually does not perform any computation, it is being used to display some info to the user.
678 So this task should be **always** executed.
679
680 ``uptodate`` will be explained in detail in part 2 of this tutorial.
681 For now it suffices to add the value ``False`` to indicate this task will never be considered **up-do-date**.
682
683 .. code-block:: python
684
685 'uptodate': [False],
686
687
688 verbosity
689 ---------
690
691 ``doit`` output (for command ``run``) consists of:
692
693 - one line with task name (preceded by `.` or `--`)
694 - task's output
695
696 The actual task's output displayed can be controlled by ``verbosity``.
697 There are 3 levels of verbosity.
698
699 - 0: both stdout and stderr from the task are **NOT** displayed
700 - 1: only stderr is displayed
701 - 2: both stdout and stderr are displayed
702
703 The default verbosity is `1`.
704
705 If the ``print`` task would be executed with the default verbosity we would actually not see any output, so we must force its ``verbosity`` value to ``2``.
706
707
708 .. code-block:: python3
709
710 'verbosity': 2,
711
712 .. code-block:: console
713
714 $ doit print:requests.models
715 -- imports:requests.models
716 . print:requests.models
717 requests._internal_utils
718 requests.auth
719 requests.compat
720 requests.cookies
721 requests.exceptions
722 requests.hooks
723 requests.status_codes
724 requests.structures
725 requests.utils
726
727 Note ``verbosity`` can be overwritten from command-line with option ``-v/--verbosity``.
728
729
730 DOIT_CONFIG
731 -----------
732
733 There is one last problem to be solved.
734 Since ``print`` is used only to display some information, it should not be executed by default. It should be executed only when explicitly asked.
735
736 i.e. when you just run ``doit`` without any parameters it should create the graph image but not print out the information from ``print`` task.
737
738 Before I said that by default ``doit run`` would execute all tasks.
739 That is not exactly true... it will execute all *default tasks*.
740 The default tasks can be controlled by adding a configuration dictionary with the name ``DOIT_CONFIG`` in the `dodo.py`.
741
742
743 .. DOIT_CONFIG
744 .. literalinclude:: tutorial/tuto_1_4.py
745 :language: python3
746 :lines: 7-9
747
748
749 Apart from ``default_tasks``, ``DOIT_CONFIG`` can change the default of any command line option. For example you can globally change every task's ``verbosity`` level:
750
751 .. code-block:: python3
752
753 DOIT_CONFIG = {
754 'default_tasks': ['imports', 'dot', 'draw'],
755 'verbosity': 2,
756 }
757
758
759 Code :download:`dodo.py <tutorial/tuto_1_4.py>`.
760
761
762
763 And that's all for part 1 of tutorial :)