mkinit icon indicating copy to clipboard operation
mkinit copied to clipboard

Variables with a type annotation are not imported

Open alessio-locatelli opened this issue 1 year ago • 2 comments

Describe the bug

Sorry, I did not check the source code, but most likely you parse something like variable = ... and do not expect to see variable: type_hint = ....

  1. Create a file with a variable that has a type annotation (e.g. FOOBAR: list[str] = convert_to_list(os.environ("SPAMEGGS")).
  2. Run mkinit --nomods --relative --recursive -w path_to_a_folder/

To Reproduce

FOO = 42  # This will be auto-added to the __init__.py
BAR: Final =  my_function(os.getenv("SPAMEGGS"))  # This will *NOT* be added to the __init__.py

Expected behavior

Both FOO and BAR variables must be added to the __init__.py.

Desktop

  • OS: Debian GNU/Linux 12 (bookworm)
  • mkinit version 1.1.0
  • Python version 3.12.3

Additional context

Not related to this issue, but I noticed that the --write flag overwrites the __ignore__ variable that I created manually to skip some imports. I am not sure if this a bug or a feature, but a bit annoying because each time I need to restore my __ignore__ = ["foo", "bar", "spam", "eggs"] variable.
For example, mkinit keeps the top-level comment (this is awesome!), but it could also keep the __ignore__ variable. Do I need to create a dedicated issue?

alessio-locatelli avatar May 17 '24 15:05 alessio-locatelli

Thanks for the report.

The module uses AST to parse the file, so if it is failing to find something, it is probably an issue in mkinit.top_level_ast.TopLevelVisitor.

The --write should not overwrite any user specified dunder variables like __ignore__. If it is doing this, then it is a bug. I think I have noticed this, but I've worked around it by putting a comment after the lines I don't want modified. It should be the case that it will at least find the last comment only rewrite everything after that point. A separate issue would be good to track it.

Erotemic avatar May 17 '24 16:05 Erotemic

I think I've found the issue, although I don't have a fix for mkinit yet. But while debugging an issue in ubelt, I realized that the visit_Assign method in the ast.NodeVisitor does not see assignments with annotations. Those are instead handled by a visit_AnnAssign method.

I'm fairly sure the fix here is to find the ast.NodeVisitor class that is causing the issue and add the visit_AnnAssign method that works in a similar way to an existing visit_Assign method. Help with making this change in a PR would be appreciated.

Erotemic avatar Jun 07 '24 23:06 Erotemic