jendrikseipp / vulture

Find dead Python code
MIT License
3.38k stars 148 forks source link

Basic match statement support #291

Closed kreathon closed 1 year ago

kreathon commented 1 year ago

Example

@dataclass
class X:
    a: int

x = input()

match x:
    case X(a=0):
        ...
    case _:
        ...

At the moment, a would be seen as unused. However, as nicely described by @exoriente, the code means something like

    if is_instance(x, X) and x.a == 0:

So it is not a normal / dead "assignment" and a should not be seen as unused.

Implementation

The actual code change is really trivial, since most of the desired behavior (for the match statement) is already handled by visit_Name:

    def visit_MatchClass(self, node):
        for kwd_attr in node.kwd_attrs:
            self.used_names.add(kwd_attr)

Limitations

Python Compatibility

For Python < 3.10 the visit_MatchClass should never be executed. Tests are guarded with @pytest.mark.skipif( sys.version_info < (3, 10), ...)

Related Issue

This PR is addressing the issue https://github.com/jendrikseipp/vulture/issues/276.

Checklist:

codecov-commenter commented 1 year ago

Codecov Report

Merging #291 (a362a25) into main (e3d2da3) will increase coverage by 0.00%. The diff coverage is 100.00%.

@@           Coverage Diff           @@
##             main     #291   +/-   ##
=======================================
  Coverage   99.38%   99.38%           
=======================================
  Files          19       19           
  Lines         647      651    +4     
=======================================
+ Hits          643      647    +4     
  Misses          4        4           
Impacted Files Coverage Δ
vulture/core.py 99.40% <100.00%> (+<0.01%) :arrow_up:
vulture/whitelists/ast_whitelist.py 100.00% <100.00%> (ø)

:mega: We’re building smart automated test selection to slash your CI/CD build times. Learn more

jendrikseipp commented 1 year ago

Great! Thanks @kreathon !

exoriente commented 1 year ago

:star_struck: Awesome! Nice to see this addressed! Thanks, for taking up this issue @jendrikseipp & @kreathon !