jendrikseipp / vulture

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

vulture does not detect code usage by `case` clauses in pattern matching #276

Open exoriente opened 2 years ago

exoriente commented 2 years ago

Hi,

I'm running into a issue with pattern matching and vulture. In my case the property of a class is only used during pattern matching. Vulture doesn't pick up on it and considers it dead code. I've whitelisted the properties for now, but it would be great if vulture could be improved to cover this new scenario.

Pseudo code example:

@dataclass
class MyClass
    my_field: MyType

    @property
    my_test(self) -> bool:
        return my_field == my_constant

def do_something(x: Object) -> None:
    match x:
        case MyClass(my_test=True):
            do_stuff(x)
        case MyClass(my_test=False):
            do_other_stuff(x)

In this example, vulture seems to flag my_test as dead code.

jendrikseipp commented 2 years ago

Thanks for the report! We haven't added explicit support for the match statement, yet, so there could be room for improvement.

But in your code, I think my_test is really unused. Shouldn't the my_test={True,False} kwarg be called my_field?

exoriente commented 2 years ago

Nope. It is used. The syntax decided for pattern matching is a bit counterintuitive.

In this example:

    case MyClass(my_test=True):

is more or less equivalent to:

    if is_instance(x, MyClass):
        if x.my_test == True:

I also had to get used to this. It seems like you're making a new MyClass object to compare against, but it works a bit differently. Helpful intro here, in case you're curious.

jendrikseipp commented 2 years ago

Thanks for the explanation! Yes, then probably Vulture could be changed so that this case is detected.