snok / flake8-type-checking

Flake8 plugin for managing type-checking imports & forward references.
BSD 3-Clause "New" or "Revised" License
113 stars 16 forks source link

Add the ability to return a path by template `type-checking-exempt-modules` #154

Closed KozyrevIvan closed 1 year ago

KozyrevIvan commented 1 year ago

Add the ability to return a path by template

type-checking-exempt-modules = apps.*.choices, *.choices

sondrelg commented 1 year ago

How would you parse the expressions? Are there any de facto standard libraries for this?

KozyrevIvan commented 1 year ago

For development, we use Django, which consists of several applications. For convenience and to reduce cyclic imports, choices were moved to a separate module, as a result of which the project structure turned out to be something like this:

...
apps
 +-  app_1
        +-  ...
        +- choices.py
        +- typengs.py
        +-...
 +-  app_2
        +-  ...
        +- choices.py
        +- typengs.py
        +-...
...

And now you have to register each module separately.

type-checking-exempt-modules = 
   ...
   apps.app_1.choices,
   apps.app_2.choices,
   apps.app_1.typengs,
   apps.app_2.typengs,
   ...

But it should look like this.

type-checking-exempt-modules = 
   ...
   apps.*.choices,
   apps.*.typengs,
   ...

I think it can be done like this. Example:

if (
    isinstance(node, ast.Import) 
    and any(
         {exempt_module for exempt_module in self.exempt_modules if re.match(name_node.name, exempt_module)}
    )
):
     return
sondrelg commented 1 year ago

I've also seen fnmatch used for this - not sure which is better yet, but just remembered :slightly_smiling_face:

I think this would be a nice feature to add. Would you be interested in creating a PR for it?

sondrelg commented 1 year ago

That was fast @KozyrevIvan! Thanks :clap: