ts-node-action icon indicating copy to clipboard operation
ts-node-action copied to clipboard

[python] cycle import style

Open alexpw opened this issue 1 year ago • 4 comments

Python import statements can be written in a few different styles. Initially, I wanted the equivalent of toggle_multiline() for import_from_statements between "inline" and "expand" (see Formats), but certain style guides prefer a "single" style (one import per line). There are other preferences, like whether a multi-line statement is wrapped in parentheses or uses \ for line continuation, and it also needs to account for a max line_length. So I wrote up something custom to cycle between them, and made it configurable.

Formats

import_statement

  • "single"
import json
import xml
  • "inline"
import json, xml

import_from_statement

  • "single"
from json import loads
from json import dumps
  • "inline"
from json import loads, dumps
  • "expand"
from json import (
    loads,
    dumps,
)

Siblings

cycle_import() will look for and include siblings that are adjacent to the node performing the action. Siblings have the same :type() and import from the same module/package. This is what enables the "single" format to participate in cycling. For example, going from "single" to "inline":

from json import loads
from json import dumps
from json import loads, dumps

isn't possible without being able to combine* the two.

*Implementation Note:

There is no appropriate parent to act as a target node that could provide the correct node:range() for init.lua:replace_node(), so in this case, it creates a table in make_target_node() that responds to :range() with the correct start/end positions (and more, see comments).

alexpw avatar Mar 06 '23 07:03 alexpw