nhoad / flake8-unused-arguments

Flake8 plugin to warn against unused arguments in functions
MIT License
31 stars 8 forks source link

Handling of __exit__ #4

Closed spreiter closed 4 years ago

spreiter commented 4 years ago

The __exit__() function does not explicitly need 3 arguments, but it should in order to handle exceptions correctly.

Can this function be handled separately?

Doc: https://docs.python.org/3.8/reference/datamodel.html#with-statement-context-managers

nhoad commented 4 years ago

Could you clarify what you're asking for? I'm not sure what you mean by "handled separately".

Also, __exit__() definitely needs three arguments, regardless of whether or not an exception has occurred. As the documentation says, the three values will be None if no error occurred.

spreiter commented 4 years ago

Currently the __exit__() function is detected as unused arguments, but they have to be there. I think in Python 2, it was also allowed to have 0 arguments. But anyhow.

The plugins detects the following example as unused arguments, but I would like the plugin to ignore it only for the __exit__() function.

def __exit__(self, exc_type, exc_value, traceback):
    print('closing...')
nhoad commented 4 years ago

I don't support Python 2, but it required all the arguments as well. __exit__() isn't a special case, it just happens to have unused arguments for your situation. If you'd like to ignore unused arguments, you can prefix them with an underscore and then ignore error U101:

$ cat testing.py
class foo:
    def __enter__(self):
        return 5

    def __exit__(self, _a, _b, _c):
        pass

class bar:
    def __enter__(self):
        return 5

    def __exit__(self, a, b, c):
        pass
$ flake8 testing.py
testing.py:5:24: U101 Unused argument '_a'
testing.py:5:28: U101 Unused argument '_b'
testing.py:5:32: U101 Unused argument '_c'
testing.py:13:24: U100 Unused argument 'a'
testing.py:13:27: U100 Unused argument 'b'
testing.py:13:30: U100 Unused argument 'c'
$ flake8 testing.py --ignore U101
testing.py:13:24: U100 Unused argument 'a'
testing.py:13:27: U100 Unused argument 'b'
testing.py:13:30: U100 Unused argument 'c'
$
spreiter commented 4 years ago

Ok. Since __exit__() always requires exactly 3 arguments, I though an exception for this specific case would be convenient.

I will handle it different. Thanks