Skip to content

Conversation

@alexpw
Copy link
Contributor

@alexpw alexpw commented Mar 6, 2023

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).

@CKolkey
Copy link
Owner

CKolkey commented Mar 6, 2023

Just go ahead and request a review when you feel its ready :)

@alexpw alexpw marked this pull request as draft March 6, 2023 20:21
@alexpw
Copy link
Contributor Author

alexpw commented Mar 6, 2023

Thanks, I thought it was ready, but the format detection needs more testing / thought to stabilize.

I can't add reviewers, but I can use the draft status and mark it "Ready for review" soon (tm).

@CKolkey
Copy link
Owner

CKolkey commented Mar 6, 2023

You can't? Huh, wonder what I need to set to enable that. Until then, draft is fine :)

@alexpw alexpw marked this pull request as ready for review March 13, 2023 03:31
@alexpw
Copy link
Contributor Author

alexpw commented Mar 13, 2023

Sorry for a massive diff. I moved* code, so turning off whitespace in the PR tab will hopefully help (Gear -> "Hide Whitespace").

*python.lua had grown too big, so I moved the if/else code to python/conditional.lua and created a python/node_utils.lua to share node related functions. I had fun with an approach for iterating over nodes that might've turned out well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants