extract code-blocks from the given docstring. DON'T include the multiline-string definition in code-blocks. The *Examples* section must be the last. Args: docstr(str): docstring google_style(bool): if not use google_style, the code blocks will be extracted from all t
(docstr, google_style=True)
| 417 | |
| 418 | |
| 419 | def extract_code_blocks_from_docstr(docstr, google_style=True): |
| 420 | """ |
| 421 | extract code-blocks from the given docstring. |
| 422 | DON'T include the multiline-string definition in code-blocks. |
| 423 | The *Examples* section must be the last. |
| 424 | Args: |
| 425 | docstr(str): docstring |
| 426 | google_style(bool): if not use google_style, the code blocks will be extracted from all the parts of docstring. |
| 427 | Return: |
| 428 | code_blocks: A list of code-blocks, indent removed. |
| 429 | element {'name': the code-block's name, 'id': sequence id. |
| 430 | 'codes': codes, 'in_examples': bool, code block in `Examples` or not,} |
| 431 | """ |
| 432 | code_blocks = [] |
| 433 | |
| 434 | mo = re.search(r"Examples?:", docstr) |
| 435 | |
| 436 | if google_style and mo is None: |
| 437 | return code_blocks |
| 438 | |
| 439 | example_start = len(docstr) if mo is None else mo.start() |
| 440 | docstr_describe = docstr[:example_start].splitlines() |
| 441 | docstr_examples = docstr[example_start:].splitlines() |
| 442 | |
| 443 | docstr_list = [] |
| 444 | if google_style: |
| 445 | example_lineno = 0 |
| 446 | docstr_list = docstr_examples |
| 447 | else: |
| 448 | example_lineno = len(docstr_describe) |
| 449 | docstr_list = docstr_describe + docstr_examples |
| 450 | |
| 451 | lastlineindex = len(docstr_list) - 1 |
| 452 | |
| 453 | cb_start_pat = re.compile(r"code-block::\s*(python|python-console|pycon)") |
| 454 | cb_param_pat = re.compile(r"^\s*:(\w+):\s*(\S*)\s*$") |
| 455 | |
| 456 | cb_info = {} |
| 457 | cb_info['cb_started'] = False |
| 458 | cb_info['cb_cur'] = [] |
| 459 | cb_info['cb_cur_indent'] = -1 |
| 460 | cb_info['cb_cur_name'] = None |
| 461 | cb_info['cb_cur_seq_id'] = 0 |
| 462 | |
| 463 | def _cb_started(): |
| 464 | # nonlocal cb_started, cb_cur_name, cb_cur_seq_id |
| 465 | cb_info['cb_started'] = True |
| 466 | cb_info['cb_cur_seq_id'] += 1 |
| 467 | cb_info['cb_cur_name'] = None |
| 468 | |
| 469 | def _append_code_block(in_examples): |
| 470 | # nonlocal code_blocks, cb_cur, cb_cur_name, cb_cur_seq_id |
| 471 | code_blocks.append( |
| 472 | { |
| 473 | 'codes': inspect.cleandoc("\n" + "\n".join(cb_info['cb_cur'])), |
| 474 | 'name': cb_info['cb_cur_name'], |
| 475 | 'id': cb_info['cb_cur_seq_id'], |
| 476 | 'in_examples': in_examples, |
no test coverage detected