|
13 | 13 | # limitations under the License. |
14 | 14 | # ============================================================================== |
15 | 15 | """Format notebook code cells using yapf google style.""" |
| 16 | + |
16 | 17 | import glob |
17 | 18 | import nbformat |
18 | 19 | import yapf |
19 | 20 |
|
20 | | -# Must be run from the top level of the `TFQuantum` repo. |
21 | | -NOTEBOOKS = glob.glob("docs/tutorials/*.ipynb") |
22 | | -for fname in NOTEBOOKS: |
23 | | - nb = nbformat.read(fname, as_version=nbformat.NO_CONVERT) |
24 | | - all_cells = nb.get('cells') |
25 | | - for i, cell in enumerate(all_cells): |
26 | | - if cell.get('cell_type') != 'code': |
27 | | - continue |
28 | | - lines = cell.get('source') |
29 | | - # This will safely skip over cells containing !% magic |
30 | | - try: |
31 | | - fmt_lines = yapf.yapf_api.FormatCode(''.join(lines), |
32 | | - style_config="google")[0] |
33 | | - except (SyntaxError, yapf.yapflib.errors.YapfError): |
34 | | - continue |
35 | | - # google style always adds an EOF newline; undo this. |
36 | | - all_cells[i]['source'] = fmt_lines[:-1] |
37 | | - |
38 | | - nb['cells'] = all_cells |
39 | | - nbformat.write(nb, fname, version=nbformat.NO_CONVERT) |
| 21 | + |
| 22 | +def format_notebooks(): |
| 23 | + """Format tutorial notebooks. |
| 24 | +
|
| 25 | + This must be run from the top level of the repository.""" |
| 26 | + |
| 27 | + for fname in glob.glob("docs/tutorials/*.ipynb"): |
| 28 | + nb = nbformat.read(fname, as_version=nbformat.NO_CONVERT) |
| 29 | + all_cells = nb.get('cells') |
| 30 | + for i, cell in enumerate(all_cells): |
| 31 | + if cell.get('cell_type') != 'code': |
| 32 | + continue |
| 33 | + lines = cell.get('source') |
| 34 | + # This will safely skip over cells containing !% magic |
| 35 | + try: |
| 36 | + fmt_lines = yapf.yapf_api.FormatCode(''.join(lines), |
| 37 | + style_config="google")[0] |
| 38 | + except (SyntaxError, yapf.yapflib.errors.YapfError): |
| 39 | + continue |
| 40 | + # google style always adds an EOF newline; undo this. |
| 41 | + all_cells[i]['source'] = fmt_lines[:-1] |
| 42 | + |
| 43 | + nb['cells'] = all_cells |
| 44 | + nbformat.write(nb, fname, version=nbformat.NO_CONVERT) |
| 45 | + |
| 46 | + |
| 47 | +if __name__ == "__main__": |
| 48 | + format_notebooks() |
0 commit comments