|
14 | 14 |
|
15 | 15 | from io import StringIO |
16 | 16 | from pathlib import Path |
17 | | -from typing import Type |
| 17 | +from typing import Iterable, Type |
18 | 18 | from urllib.parse import urlparse |
19 | 19 |
|
20 | 20 | import networkx as nx |
@@ -798,3 +798,41 @@ def generate_footer() -> str: |
798 | 798 | </a> |
799 | 799 | </footer>""" |
800 | 800 | return footer |
| 801 | + |
| 802 | + |
| 803 | +def sort_imports(imp: Iterable[str]) -> tuple[list[str], list[str]]: |
| 804 | + """Separte 'from' and 'import' statements from setup code. |
| 805 | +
|
| 806 | + Parameters |
| 807 | + ---------- |
| 808 | + imp : Iterable[str] |
| 809 | + A list of import statements and setup statements. |
| 810 | +
|
| 811 | + Returns |
| 812 | + ------- |
| 813 | + Tuple[List[str], List[str]] |
| 814 | + A tuple of two lists: one for import statements and one for setup statements. |
| 815 | +
|
| 816 | + Examples |
| 817 | + -------- |
| 818 | + >>> imp = [ |
| 819 | + ... 'import logging', |
| 820 | + ... 'import shutil', |
| 821 | + ... 'logging.basicConfig(level=logging.INFO)', |
| 822 | + ... 'import pandas as pd', |
| 823 | + ... 'import numpy as np', |
| 824 | + ... ] |
| 825 | + >>> sort_imports(imp) |
| 826 | + (['import logging', 'import numpy as np', 'import pandas as pd', 'import shutil |
| 827 | + ], ['logging.basicConfig(level=logging.INFO)']) |
| 828 | + """ |
| 829 | + imports_statements, setup_statements = [], [] |
| 830 | + for line in imp: |
| 831 | + line = line.strip() # just for safety |
| 832 | + if line.startswith("from ") or line.startswith("import "): |
| 833 | + imports_statements.append(line) |
| 834 | + else: |
| 835 | + setup_statements.append(line) |
| 836 | + imports_statements.sort() |
| 837 | + setup_statements.sort() |
| 838 | + return imports_statements, setup_statements |
0 commit comments