Skip to content

Module isort.identify

Fast stream based import identification.

Eventually this will likely replace parse.py

View Source
"""Fast stream based import identification.

Eventually this will likely replace parse.py

"""

from functools import partial

from pathlib import Path

from typing import Iterator, NamedTuple, Optional, TextIO, Tuple

from isort.parse import _normalize_line, _strip_syntax, skip_line

from .comments import parse as parse_comments

from .settings import DEFAULT_CONFIG, Config

STATEMENT_DECLARATIONS: Tuple[str, ...] = ("def ", "cdef ", "cpdef ", "class ", "@", "async def")

class Import(NamedTuple):

    line_number: int

    indented: bool

    module: str

    attribute: Optional[str] = None

    alias: Optional[str] = None

    cimport: bool = False

    file_path: Optional[Path] = None

    def statement(self) -> str:

        import_cmd = "cimport" if self.cimport else "import"

        if self.attribute:

            import_string = f"from {self.module} {import_cmd} {self.attribute}"

        else:

            import_string = f"{import_cmd} {self.module}"

        if self.alias:

            import_string += f" as {self.alias}"

        return import_string

    def __str__(self) -> str:

        return (

            f"{self.file_path or ''}:{self.line_number} "

            f"{'indented ' if self.indented else ''}{self.statement()}"

        )

def imports(

    input_stream: TextIO,

    config: Config = DEFAULT_CONFIG,

    file_path: Optional[Path] = None,

    top_only: bool = False,

) -> Iterator[Import]:

    """Parses a python file taking out and categorizing imports."""

    in_quote = ""

    indexed_input = enumerate(input_stream)

    for index, raw_line in indexed_input:

        (skipping_line, in_quote) = skip_line(

            raw_line, in_quote=in_quote, index=index, section_comments=config.section_comments

        )

        if top_only and not in_quote and raw_line.startswith(STATEMENT_DECLARATIONS):

            break

        if skipping_line:

            continue

        stripped_line = raw_line.strip().split("#")[0]

        if stripped_line.startswith("raise") or stripped_line.startswith("yield"):

            if stripped_line == "yield":

                while not stripped_line or stripped_line == "yield":

                    try:

                        index, next_line = next(indexed_input)

                    except StopIteration:

                        break

                    stripped_line = next_line.strip().split("#")[0]

            while stripped_line.endswith("\\"):

                try:

                    index, next_line = next(indexed_input)

                except StopIteration:

                    break

                stripped_line = next_line.strip().split("#")[0]

            continue  # pragma: no cover

        line, *end_of_line_comment = raw_line.split("#", 1)

        statements = [line.strip() for line in line.split(";")]

        if end_of_line_comment:

            statements[-1] = f"{statements[-1]}#{end_of_line_comment[0]}"

        for statement in statements:

            line, _raw_line = _normalize_line(statement)

            if line.startswith(("import ", "cimport ")):

                type_of_import = "straight"

            elif line.startswith("from "):

                type_of_import = "from"

            else:

                continue  # pragma: no cover

            import_string, _ = parse_comments(line)

            normalized_import_string = (

                import_string.replace("import(", "import (").replace("\\", " ").replace("\n", " ")

            )

            cimports: bool = (

                " cimport " in normalized_import_string

                or normalized_import_string.startswith("cimport")

            )

            identified_import = partial(

                Import,

                index + 1,  # line numbers use 1 based indexing

                raw_line.startswith((" ", "\t")),

                cimport=cimports,

                file_path=file_path,

            )

            if "(" in line.split("#", 1)[0]:

                while not line.split("#")[0].strip().endswith(")"):

                    try:

                        index, next_line = next(indexed_input)

                    except StopIteration:

                        break

                    line, _ = parse_comments(next_line)

                    import_string += "\n" + line

            else:

                while line.strip().endswith("\\"):

                    try:

                        index, next_line = next(indexed_input)

                    except StopIteration:

                        break

                    line, _ = parse_comments(next_line)

                    # Still need to check for parentheses after an escaped line

                    if "(" in line.split("#")[0] and ")" not in line.split("#")[0]:

                        import_string += "\n" + line

                        while not line.split("#")[0].strip().endswith(")"):

                            try:

                                index, next_line = next(indexed_input)

                            except StopIteration:

                                break

                            line, _ = parse_comments(next_line)

                            import_string += "\n" + line

                    else:

                        if import_string.strip().endswith(

                            (" import", " cimport")

                        ) or line.strip().startswith(("import ", "cimport ")):

                            import_string += "\n" + line

                        else:

                            import_string = (

                                import_string.rstrip().rstrip("\\") + " " + line.lstrip()

                            )

            if type_of_import == "from":

                import_string = (

                    import_string.replace("import(", "import (")

                    .replace("\\", " ")

                    .replace("\n", " ")

                )

                parts = import_string.split(" cimport " if cimports else " import ")

                from_import = parts[0].split(" ")

                import_string = (" cimport " if cimports else " import ").join(

                    [from_import[0] + " " + "".join(from_import[1:])] + parts[1:]

                )

            just_imports = [

                item.replace("{|", "{ ").replace("|}", " }")

                for item in _strip_syntax(import_string).split()

            ]

            direct_imports = just_imports[1:]

            top_level_module = ""

            if "as" in just_imports and (just_imports.index("as") + 1) < len(just_imports):

                while "as" in just_imports:

                    attribute = None

                    as_index = just_imports.index("as")

                    if type_of_import == "from":

                        attribute = just_imports[as_index - 1]

                        top_level_module = just_imports[0]

                        module = top_level_module + "." + attribute

                        alias = just_imports[as_index + 1]

                        direct_imports.remove(attribute)

                        direct_imports.remove(alias)

                        direct_imports.remove("as")

                        just_imports[1:] = direct_imports

                        if attribute == alias and config.remove_redundant_aliases:

                            yield identified_import(top_level_module, attribute)

                        else:

                            yield identified_import(top_level_module, attribute, alias=alias)

                    else:

                        module = just_imports[as_index - 1]

                        alias = just_imports[as_index + 1]

                        just_imports.remove(alias)

                        just_imports.remove("as")

                        just_imports.remove(module)

                        if module == alias and config.remove_redundant_aliases:

                            yield identified_import(module)

                        else:

                            yield identified_import(module, alias=alias)

            if just_imports:

                if type_of_import == "from":

                    module = just_imports.pop(0)

                    for attribute in just_imports:

                        yield identified_import(module, attribute)

                else:

                    for module in just_imports:

                        yield identified_import(module)

Variables

STATEMENT_DECLARATIONS

Functions

imports

def imports(
    input_stream: <class 'TextIO'>,
    config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'build', '.pants.d', '.mypy_cache', 'buck-out', '.nox', '.eggs', '.git', 'venv', '.tox', '.direnv', 'dist', '.venv', '.hg', '__pypackages__', '.bzr', 'node_modules', '_build', '.svn'}), extend_skip=frozenset(), skip_glob=frozenset(), extend_skip_glob=frozenset(), skip_gitignore=False, line_length=79, wrap_length=0, line_ending='', sections=('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), no_sections=False, known_future_library=frozenset({'__future__'}), known_third_party=frozenset(), known_first_party=frozenset(), known_local_folder=frozenset(), known_standard_library=frozenset({'getopt', 'mailcap', 'imaplib', 'nntplib', 'filecmp', 'threading', 'fnmatch', 'timeit', 'sqlite3', 'configparser', 'bdb', 'runpy', 'chunk', 'curses', 'ntpath', 'posixpath', 'platform', 'html', 'fractions', 'tomllib', 'token', 'zlib', 'code', 'poplib', 'fcntl', 'numbers', 'select', 'codecs', 'binascii', 'weakref', 'zipfile', 'distutils', 'secrets', 'sunau', '_ast', 'smtpd', 'dataclasses', 'http', 'gzip', 'posix', 'functools', 'zoneinfo', 'inspect', 'cgitb', 'symtable', 'pathlib', 'unittest', 'itertools', 'operator', 'fpectl', 'linecache', 'encodings', 'sys', 'resource', 'errno', 'telnetlib', 'traceback', 'idlelib', 'warnings', 'sre', 'io', 'cgi', 'email', 'sre_parse', 'dbm', 'pickletools', 'wsgiref', 'turtledemo', 'optparse', 'concurrent', 'string', 'statistics', 'subprocess', 'modulefinder', 'mailbox', 'lib2to3', 'colorsys', 'signal', 'time', 'shelve', 'calendar', 'pipes', 'importlib', 'unicodedata', 'gc', 'crypt', 'msvcrt', 'csv', 'ossaudiodev', 'msilib', 'pickle', 'hashlib', 'nis', 'aifc', 'hmac', 'winsound', 'graphlib', 'zipapp', 'typing', 'contextvars', 'struct', 'netrc', 'turtle', 'dummy_threading', 'cmath', 'array', 'copy', 'pydoc', 'pstats', 'grp', 'tarfile', 'copyreg', 'uu', 'zipimport', 'tabnanny', 'pyclbr', 'getpass', 'keyword', 'mmap', 'spwd', 'codeop', 'sre_compile', 'dis', 'sysconfig', 'atexit', 'venv', 'argparse', 'syslog', 'rlcompleter', 'xdrlib', 'faulthandler', 'lzma', 'macpath', 'enum', 'abc', 'ctypes', 'pprint', '_dummy_thread', 'test', 'socketserver', 'marshal', 'xml', 'binhex', 'socket', 'sched', 'textwrap', 'asyncio', 'webbrowser', 'urllib', 'pwd', 'bz2', 'cmd', 'ipaddress', 'os', 'xmlrpc', 'plistlib', 'fileinput', 'bisect', 'trace', 'gettext', 'contextlib', 'collections', 'ensurepip', 'mimetypes', 'ast', 'sndhdr', 'asyncore', 'difflib', 'tty', 'multiprocessing', 'site', '_thread', 'pkgutil', 'readline', 'stat', 'tokenize', 'smtplib', 'heapq', 'queue', 'shutil', 'termios', 'quopri', 'types', 'profile', 'tkinter', 'symbol', 'cProfile', 'sre_constants', 'formatter', 'locale', 'ssl', 'tempfile', 'stringprep', 'random', 'datetime', 'compileall', 'asynchat', 'tracemalloc', 'imp', 'decimal', 'imghdr', 'py_compile', 'pdb', 'shlex', 'selectors', 'wave', 'reprlib', 'winreg', 'logging', 'math', 'glob', 're', 'audioop', 'ftplib', 'base64', 'parser', 'pty', 'doctest', 'uuid', 'builtins', 'json'}), extra_standard_library=frozenset(), known_other={}, multi_line_output=<WrapModes.GRID: 0>, forced_separate=(), indent='    ', comment_prefix='  #', length_sort=False, length_sort_straight=False, length_sort_sections=frozenset(), add_imports=frozenset(), remove_imports=frozenset(), append_only=False, reverse_relative=False, force_single_line=False, single_line_exclusions=(), default_section='THIRDPARTY', import_headings={}, import_footers={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, lines_before_imports=-1, lines_after_imports=-1, lines_between_sections=1, lines_between_types=0, combine_as_imports=False, combine_star=False, include_trailing_comma=False, from_first=False, verbose=False, quiet=False, force_adds=False, force_alphabetical_sort_within_sections=False, force_alphabetical_sort=False, force_grid_wrap=0, force_sort_within_sections=False, lexicographical=False, group_by_package=False, ignore_whitespace=False, no_lines_before=frozenset(), no_inline_sort=False, ignore_comments=False, case_sensitive=False, sources=({'py_version': 'py3', 'force_to_top': frozenset(), 'skip': frozenset({'build', '.pants.d', '.mypy_cache', 'buck-out', '.nox', '.eggs', '.git', 'venv', '.tox', '.direnv', 'dist', '.venv', '.hg', '__pypackages__', '.bzr', 'node_modules', '_build', '.svn'}), 'extend_skip': frozenset(), 'skip_glob': frozenset(), 'extend_skip_glob': frozenset(), 'skip_gitignore': False, 'line_length': 79, 'wrap_length': 0, 'line_ending': '', 'sections': ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), 'no_sections': False, 'known_future_library': frozenset({'__future__'}), 'known_third_party': frozenset(), 'known_first_party': frozenset(), 'known_local_folder': frozenset(), 'known_standard_library': frozenset({'getopt', 'mailcap', 'imaplib', 'nntplib', 'filecmp', 'threading', 'fnmatch', 'timeit', 'sqlite3', 'configparser', 'bdb', 'runpy', 'chunk', 'curses', 'ntpath', 'posixpath', 'platform', 'html', 'fractions', 'tomllib', 'token', 'zlib', 'code', 'poplib', 'fcntl', 'numbers', 'select', 'codecs', 'binascii', 'weakref', 'zipfile', 'distutils', 'secrets', 'sunau', '_ast', 'smtpd', 'dataclasses', 'http', 'gzip', 'posix', 'functools', 'zoneinfo', 'inspect', 'cgitb', 'symtable', 'pathlib', 'unittest', 'itertools', 'operator', 'fpectl', 'linecache', 'encodings', 'sys', 'resource', 'errno', 'telnetlib', 'traceback', 'idlelib', 'warnings', 'sre', 'io', 'cgi', 'email', 'sre_parse', 'dbm', 'pickletools', 'wsgiref', 'turtledemo', 'optparse', 'concurrent', 'string', 'statistics', 'subprocess', 'modulefinder', 'mailbox', 'lib2to3', 'colorsys', 'signal', 'time', 'shelve', 'calendar', 'pipes', 'importlib', 'unicodedata', 'gc', 'crypt', 'msvcrt', 'csv', 'ossaudiodev', 'msilib', 'pickle', 'hashlib', 'nis', 'aifc', 'hmac', 'winsound', 'graphlib', 'zipapp', 'typing', 'contextvars', 'struct', 'netrc', 'turtle', 'dummy_threading', 'cmath', 'array', 'copy', 'pydoc', 'pstats', 'grp', 'tarfile', 'copyreg', 'uu', 'zipimport', 'tabnanny', 'pyclbr', 'getpass', 'keyword', 'mmap', 'spwd', 'codeop', 'sre_compile', 'dis', 'sysconfig', 'atexit', 'venv', 'argparse', 'syslog', 'rlcompleter', 'xdrlib', 'faulthandler', 'lzma', 'macpath', 'enum', 'abc', 'ctypes', 'pprint', '_dummy_thread', 'test', 'socketserver', 'marshal', 'xml', 'binhex', 'socket', 'sched', 'textwrap', 'asyncio', 'webbrowser', 'urllib', 'pwd', 'bz2', 'cmd', 'ipaddress', 'os', 'xmlrpc', 'plistlib', 'fileinput', 'bisect', 'trace', 'gettext', 'contextlib', 'collections', 'ensurepip', 'mimetypes', 'ast', 'sndhdr', 'asyncore', 'difflib', 'tty', 'multiprocessing', 'site', '_thread', 'pkgutil', 'readline', 'stat', 'tokenize', 'smtplib', 'heapq', 'queue', 'shutil', 'termios', 'quopri', 'types', 'profile', 'tkinter', 'symbol', 'cProfile', 'sre_constants', 'formatter', 'locale', 'ssl', 'tempfile', 'stringprep', 'random', 'datetime', 'compileall', 'asynchat', 'tracemalloc', 'imp', 'decimal', 'imghdr', 'py_compile', 'pdb', 'shlex', 'selectors', 'wave', 'reprlib', 'winreg', 'logging', 'math', 'glob', 're', 'audioop', 'ftplib', 'base64', 'parser', 'pty', 'doctest', 'uuid', 'builtins', 'json'}), 'extra_standard_library': frozenset(), 'known_other': {}, 'multi_line_output': <WrapModes.GRID: 0>, 'forced_separate': (), 'indent': '    ', 'comment_prefix': '  #', 'length_sort': False, 'length_sort_straight': False, 'length_sort_sections': frozenset(), 'add_imports': frozenset(), 'remove_imports': frozenset(), 'append_only': False, 'reverse_relative': False, 'force_single_line': False, 'single_line_exclusions': (), 'default_section': 'THIRDPARTY', 'import_headings': {}, 'import_footers': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, 'lines_before_imports': -1, 'lines_after_imports': -1, 'lines_between_sections': 1, 'lines_between_types': 0, 'combine_as_imports': False, 'combine_star': False, 'include_trailing_comma': False, 'from_first': False, 'verbose': False, 'quiet': False, 'force_adds': False, 'force_alphabetical_sort_within_sections': False, 'force_alphabetical_sort': False, 'force_grid_wrap': 0, 'force_sort_within_sections': False, 'lexicographical': False, 'group_by_package': False, 'ignore_whitespace': False, 'no_lines_before': frozenset(), 'no_inline_sort': False, 'ignore_comments': False, 'case_sensitive': False, 'sources': (), 'virtual_env': '', 'conda_env': '', 'ensure_newline_before_comments': False, 'directory': '', 'profile': '', 'honor_noqa': False, 'src_paths': (), 'old_finders': False, 'remove_redundant_aliases': False, 'float_to_top': False, 'filter_files': False, 'formatter': '', 'formatting_function': None, 'color_output': False, 'treat_comments_as_code': frozenset(), 'treat_all_comments_as_code': False, 'supported_extensions': frozenset({'py', 'pyx', 'pyi', 'pxd'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'only_modified': False, 'combine_straight_imports': False, 'auto_identify_namespace_packages': True, 'namespace_packages': frozenset(), 'follow_links': True, 'indented_import_headings': True, 'honor_case_in_force_sorted_sections': False, 'sort_relative_in_force_sorted_sections': False, 'overwrite_in_place': False, 'reverse_sort': False, 'star_first': False, 'git_ls_files': {}, 'format_error': '{error}: {message}', 'format_success': '{success}: {message}', 'sort_order': 'natural', 'sort_reexports': False, 'split_on_trailing_comma': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/home/timothycrosley/Projects/isort', profile='', honor_noqa=False, src_paths=(PosixPath('/home/timothycrosley/Projects/isort/src'), PosixPath('/home/timothycrosley/Projects/isort')), old_finders=False, remove_redundant_aliases=False, float_to_top=False, filter_files=False, formatter='', formatting_function=None, color_output=False, treat_comments_as_code=frozenset(), treat_all_comments_as_code=False, supported_extensions=frozenset({'py', 'pyx', 'pyi', 'pxd'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False, only_modified=False, combine_straight_imports=False, auto_identify_namespace_packages=True, namespace_packages=frozenset(), follow_links=True, indented_import_headings=True, honor_case_in_force_sorted_sections=False, sort_relative_in_force_sorted_sections=False, overwrite_in_place=False, reverse_sort=False, star_first=False, git_ls_files={}, format_error='{error}: {message}', format_success='{success}: {message}', sort_order='natural', sort_reexports=False, split_on_trailing_comma=False),
    file_path: Optional[pathlib.Path] = None,
    top_only: bool = False
) -> Iterator[isort.identify.Import]

Parses a python file taking out and categorizing imports.

View Source
def imports(

    input_stream: TextIO,

    config: Config = DEFAULT_CONFIG,

    file_path: Optional[Path] = None,

    top_only: bool = False,

) -> Iterator[Import]:

    """Parses a python file taking out and categorizing imports."""

    in_quote = ""

    indexed_input = enumerate(input_stream)

    for index, raw_line in indexed_input:

        (skipping_line, in_quote) = skip_line(

            raw_line, in_quote=in_quote, index=index, section_comments=config.section_comments

        )

        if top_only and not in_quote and raw_line.startswith(STATEMENT_DECLARATIONS):

            break

        if skipping_line:

            continue

        stripped_line = raw_line.strip().split("#")[0]

        if stripped_line.startswith("raise") or stripped_line.startswith("yield"):

            if stripped_line == "yield":

                while not stripped_line or stripped_line == "yield":

                    try:

                        index, next_line = next(indexed_input)

                    except StopIteration:

                        break

                    stripped_line = next_line.strip().split("#")[0]

            while stripped_line.endswith("\\"):

                try:

                    index, next_line = next(indexed_input)

                except StopIteration:

                    break

                stripped_line = next_line.strip().split("#")[0]

            continue  # pragma: no cover

        line, *end_of_line_comment = raw_line.split("#", 1)

        statements = [line.strip() for line in line.split(";")]

        if end_of_line_comment:

            statements[-1] = f"{statements[-1]}#{end_of_line_comment[0]}"

        for statement in statements:

            line, _raw_line = _normalize_line(statement)

            if line.startswith(("import ", "cimport ")):

                type_of_import = "straight"

            elif line.startswith("from "):

                type_of_import = "from"

            else:

                continue  # pragma: no cover

            import_string, _ = parse_comments(line)

            normalized_import_string = (

                import_string.replace("import(", "import (").replace("\\", " ").replace("\n", " ")

            )

            cimports: bool = (

                " cimport " in normalized_import_string

                or normalized_import_string.startswith("cimport")

            )

            identified_import = partial(

                Import,

                index + 1,  # line numbers use 1 based indexing

                raw_line.startswith((" ", "\t")),

                cimport=cimports,

                file_path=file_path,

            )

            if "(" in line.split("#", 1)[0]:

                while not line.split("#")[0].strip().endswith(")"):

                    try:

                        index, next_line = next(indexed_input)

                    except StopIteration:

                        break

                    line, _ = parse_comments(next_line)

                    import_string += "\n" + line

            else:

                while line.strip().endswith("\\"):

                    try:

                        index, next_line = next(indexed_input)

                    except StopIteration:

                        break

                    line, _ = parse_comments(next_line)

                    # Still need to check for parentheses after an escaped line

                    if "(" in line.split("#")[0] and ")" not in line.split("#")[0]:

                        import_string += "\n" + line

                        while not line.split("#")[0].strip().endswith(")"):

                            try:

                                index, next_line = next(indexed_input)

                            except StopIteration:

                                break

                            line, _ = parse_comments(next_line)

                            import_string += "\n" + line

                    else:

                        if import_string.strip().endswith(

                            (" import", " cimport")

                        ) or line.strip().startswith(("import ", "cimport ")):

                            import_string += "\n" + line

                        else:

                            import_string = (

                                import_string.rstrip().rstrip("\\") + " " + line.lstrip()

                            )

            if type_of_import == "from":

                import_string = (

                    import_string.replace("import(", "import (")

                    .replace("\\", " ")

                    .replace("\n", " ")

                )

                parts = import_string.split(" cimport " if cimports else " import ")

                from_import = parts[0].split(" ")

                import_string = (" cimport " if cimports else " import ").join(

                    [from_import[0] + " " + "".join(from_import[1:])] + parts[1:]

                )

            just_imports = [

                item.replace("{|", "{ ").replace("|}", " }")

                for item in _strip_syntax(import_string).split()

            ]

            direct_imports = just_imports[1:]

            top_level_module = ""

            if "as" in just_imports and (just_imports.index("as") + 1) < len(just_imports):

                while "as" in just_imports:

                    attribute = None

                    as_index = just_imports.index("as")

                    if type_of_import == "from":

                        attribute = just_imports[as_index - 1]

                        top_level_module = just_imports[0]

                        module = top_level_module + "." + attribute

                        alias = just_imports[as_index + 1]

                        direct_imports.remove(attribute)

                        direct_imports.remove(alias)

                        direct_imports.remove("as")

                        just_imports[1:] = direct_imports

                        if attribute == alias and config.remove_redundant_aliases:

                            yield identified_import(top_level_module, attribute)

                        else:

                            yield identified_import(top_level_module, attribute, alias=alias)

                    else:

                        module = just_imports[as_index - 1]

                        alias = just_imports[as_index + 1]

                        just_imports.remove(alias)

                        just_imports.remove("as")

                        just_imports.remove(module)

                        if module == alias and config.remove_redundant_aliases:

                            yield identified_import(module)

                        else:

                            yield identified_import(module, alias=alias)

            if just_imports:

                if type_of_import == "from":

                    module = just_imports.pop(0)

                    for attribute in just_imports:

                        yield identified_import(module, attribute)

                else:

                    for module in just_imports:

                        yield identified_import(module)

Classes

Import

class Import(
    /,
    *args,
    **kwargs
)
View Source
class Import(NamedTuple):

    line_number: int

    indented: bool

    module: str

    attribute: Optional[str] = None

    alias: Optional[str] = None

    cimport: bool = False

    file_path: Optional[Path] = None

    def statement(self) -> str:

        import_cmd = "cimport" if self.cimport else "import"

        if self.attribute:

            import_string = f"from {self.module} {import_cmd} {self.attribute}"

        else:

            import_string = f"{import_cmd} {self.module}"

        if self.alias:

            import_string += f" as {self.alias}"

        return import_string

    def __str__(self) -> str:

        return (

            f"{self.file_path or ''}:{self.line_number} "

            f"{'indented ' if self.indented else ''}{self.statement()}"

        )

Ancestors (in MRO)

  • builtins.tuple

Class variables

alias
attribute
cimport
file_path
indented
line_number
module

Methods

count

def count(
    self,
    value,
    /
)

Return number of occurrences of value.

index

def index(
    self,
    value,
    start=0,
    stop=9223372036854775807,
    /
)

Return first index of value.

Raises ValueError if the value is not present.

statement

def statement(
    self
) -> str
View Source
    def statement(self) -> str:

        import_cmd = "cimport" if self.cimport else "import"

        if self.attribute:

            import_string = f"from {self.module} {import_cmd} {self.attribute}"

        else:

            import_string = f"{import_cmd} {self.module}"

        if self.alias:

            import_string += f" as {self.alias}"

        return import_string