Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def line(line: str, line_separator: str, config: Config=DEFAULT_CONFIG) -> str:
"""Returns a line wrapped to the specified line-length, if possible."""
wrap_mode = config.multi_line_output
if len(line) > config.line_length and wrap_mode != Modes.NOQA: # type: ignore
line_without_comment = line
comment = None
if "#" in line:
line_without_comment, comment = line.split("#", 1)
for splitter in ("import ", ".", "as "):
exp = r"\b" + re.escape(splitter) + r"\b"
if re.search(exp, line_without_comment) and not line_without_comment.strip().startswith(
splitter
):
line_parts = re.split(exp, line_without_comment)
if comment:
_comma_maybe = "," if config.include_trailing_comma else ""
line_parts[-1] = f"{line_parts[-1].strip()}{_comma_maybe} #{comment}"
def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedContent:
"""Parses a python file taking out and categorizing imports."""
line_separator: str = config.line_ending or _infer_line_separator(contents)
in_lines = contents.split(line_separator)
out_lines = []
original_line_count = len(in_lines)
section_comments = [f"# {heading}" for heading in config.import_headings.values()]
finder = FindersManager(config=config)
line_count = len(in_lines)
place_imports: Dict[str, List[str]] = {}
import_placements: Dict[str, str] = {}
as_map: Dict[str, List[str]] = defaultdict(list)
imports: OrderedDict[str, Dict[str, Any]] = OrderedDict()
for section in chain(config.sections, config.forced_separate):
imports[section] = {"straight": OrderedDict(), "from": OrderedDict()}
def sorted_imports(
parsed: parse.ParsedContent, config: Config = DEFAULT_CONFIG, extension: str = "py"
) -> str:
"""Adds the imports back to the file.
(at the index of the first import) sorted alphabetically and split between groups
"""
if parsed.import_index == -1:
return _output_as_string(parsed.lines_without_imports, parsed.line_separator)
formatted_output: List[str] = parsed.lines_without_imports.copy()
remove_imports = [format_simplified(removal) for removal in config.remove_imports]
sort_ignore_case = config.force_alphabetical_sort_within_sections
sections: Iterable[str] = itertools.chain(parsed.sections, config.forced_separate)
if config.no_sections:
def _config(
path: Optional[Path] = None, config: Config = DEFAULT_CONFIG, **config_kwargs
) -> Config:
if path:
if (
config is DEFAULT_CONFIG
and "settings_path" not in config_kwargs
and "settings_file" not in config_kwargs
):
config_kwargs["settings_path"] = path
if config_kwargs and config is not DEFAULT_CONFIG:
raise ValueError(
"You can either specify custom configuration options using kwargs or "
"passing in a Config object. Not Both!"
)
elif config_kwargs:
config = Config(**config_kwargs)
def initialize_options(self) -> None:
default_settings = vars(DEFAULT_CONFIG).copy()
for key, value in default_settings.items():
setattr(self, key, value)
def import_statement(
import_start: str,
from_imports: List[str],
comments: Sequence[str],
line_separator: str,
config: Config=DEFAULT_CONFIG,
multi_line_output: Optional[Modes]=None
) -> str:
"""Returns a multi-line wrapped form of the provided from import statement."""
formatter = formatter_from_string((multi_line_output or config.multi_line_output).name)
dynamic_indent = " " * (len(import_start) + 1)
indent = config.indent
line_length = config.wrap_length or config.line_length
import_statement = formatter(
statement=import_start,
imports=copy.copy(from_imports),
white_space=dynamic_indent,
indent=indent,
line_length=line_length,
comments=comments,
line_separator=line_separator,
comment_prefix=config.comment_prefix,