Skip to content

Import.statement produces invalid code #1641

@Chilipp

Description

@Chilipp

Hey @timothycrosley! Thanks a lot for this awesome project! I was just wondering about the new (and useful) function you added with version 5.7.0: find_imports_in_code (and the corresponding _stream equivalents.

Consider the following example:

from isort.api import find_imports_in_code
code = """
from typing import List
"""
imports = list(find_imports_in_code(code))
imports[0].statement()
# Output: 'import typing.List'

this (import typing.List) is invalid code. Shouldn't imports[0].statement() rather produce from typing import List?

I'd replace the statement method

isort/isort/identify.py

Lines 25 to 31 in 6230dc3

def statement(self) -> str:
full_path = self.module
if self.attribute:
full_path += f".{self.attribute}"
if self.alias:
full_path += f" as {self.alias}"
return f"{'cimport' if self.cimport else 'import'} {full_path}"

with something like

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

what do you think?

Metadata

Metadata

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions