Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

duplicate-except warning for dynamic exception handling #2174

Closed
s-hertel opened this issue Jun 8, 2018 · 1 comment
Closed

duplicate-except warning for dynamic exception handling #2174

s-hertel opened this issue Jun 8, 2018 · 1 comment

Comments

@s-hertel
Copy link

s-hertel commented Jun 8, 2018

Steps to reproduce

class Foo(Exception):
    """ Exception wrapper
    """
    def __init__(self, code):
        super(Foo, self).__init__()
        self.response = {'Error': {'Code': code}}


def dynamic_exc(code):
    """ Dynamically determine what exception
    """
    import sys
    dummy, exc, dummy = sys.exc_info()
    if isinstance(exc, Foo) and exc.response['Error']['Code'] == code:
        return Foo
    return type('OtherException', (Exception,), {})


try:
    raise Foo('403')
except dynamic_exc('403') as ex:
    print('The dynamic exception {0}'.format(ex))
except Foo as ex:
    print('Caught general Foo exception {0}'.format(ex))


try:
    raise Foo('404')
except dynamic_exc('403') as ex:
    print('The dynamic exception {0}'.format(ex))
except Foo as ex:
    print('Caught general Foo exception {0}'.format(ex))

Current behavior

W: 25, 7: Catching previously caught exception type Foo (duplicate-except)
W: 33, 7: Catching previously caught exception type Foo (duplicate-except)

pylint gives a duplicate-except warning for dynamic exceptions that may not be duplicates

Expected behavior

I would expect differentiation between dynamically handled exceptions and static duplicates like below so warnings for dynamic exceptions can be turned off without masking static duplicates.

try:
    raise Foo('404')
except Foo as ex:
    print('Caught general Foo exception {0}'.format(ex))
except Foo as ex:
    print('Caught general Foo exception {0}'.format(ex))

pylint --version output

No config file found, using default configuration
pylint 1.9.2,
astroid 1.6.5
Python 3.6.0 (default, Aug  8 2017, 09:49:26)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]
@PCManticore
Copy link
Contributor

Thanks for reporting this issue.

The problem comes from the if check you're doing in that dynamic function, which pylint has no way of understanding, especially since the information comes from sys.exc_info. I suggest just refactoring the way you're using these dynamic exceptions as it is a bit confusing on what is going to catch anyway, or just disable the error in place.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants