MartinThoma / flake8-simplify

❄ A flake8 plugin that helps you to simplify code
MIT License
186 stars 19 forks source link

Architecture: Figure out how to get context #21

Closed MartinThoma closed 3 years ago

MartinThoma commented 4 years ago

Several issues are blocked, because I don't know yet how to get context.

For example, SIM 201 prevents not a==b and suggests a != b. In general, this seems to be a good rule.

As an exception, I want to leave it like this when it's in the context of throwing exceptions:

if not (a == b):
    return ValueError("Expected a==b")

But for this I need to know that the boolean operation not (a ==b) is in the context of an if-statement.

Skylion007 commented 3 years ago

@MartinThoma Here you go. To get context you just need to extend the ASTNodeVisitor: https://stackoverflow.com/questions/43166571/getting-all-the-nodes-from-python-ast-that-correspond-to-a-particular-variable-w

Skylion007 commented 3 years ago

@MartinThoma Or better yet transformers.ParentChildNodeTransformer in astmonkey should work well. One of the AST libraries in the list should prove helpful: https://github.com/gyermolenko/awesome-python-ast

Skylion007 commented 3 years ago

After looking around, I really think astpath should be able to do queries with all the context you realistically need: (check the ReadMe: https://github.com/hchasestevens/astpath)

MartinThoma commented 3 years ago

Thank you!

This week (and probably all the time until Christmas) is super busy for me. I don't think I will have the time to look into it. But feel free to create a PR :-)

MartinThoma commented 3 years ago

https://stackoverflow.com/a/43311383/562769 might be it

MartinThoma commented 3 years ago

It's fixed: https://github.com/MartinThoma/flake8-simplify/commit/e301b8fd21a10a62de78a6b6c2437c10970ed320 - now every node has a parent attribute. It's a bit of a mess to fix the type annotations, but besides that it's fine.

Skylion007 commented 3 years ago

@MartinThoma Could have also just used typing .cast

MartinThoma commented 3 years ago

@Skylion007 Where? And cast to what? Feel free to make a PR if you see a simpler solution :-)

Skylion007 commented 3 years ago

Ah, nvm you are using dynamic attrs. Yeah, that will only work if you mark parent as an optional value and subclass them all. :/