Bug 369367

Summary: Caught exceptions get wrong scope (py3 change)
Product: [Developer tools] kdev-python Reporter: Nicolás Alvarez <nalvarez>
Component: Language supportAssignee: Sven Brauch <mail>
Status: CONFIRMED ---    
Severity: wishlist    
Priority: NOR    
Version First Reported In: 5.0.1   
Target Milestone: 1.7.3   
Platform: Other   
OS: Linux   
Latest Commit: Version Fixed/Implemented In:
Sentry Crash Report:

Description Nicolás Alvarez 2016-09-26 02:53:42 UTC
Python3 has changed the scoping for exceptions caught in an 'except..as' statement. The Python3 documentation says: "When an exception has been assigned using "as target", it is cleared at the end of the except clause. This means the exception must be assigned to a different name to be able to refer to it after the except clause."

Sample code:

try:
    a=1/0
except Exception as exc:
    print("1", exc)

print("2", exc)

If I run this on Python2, it prints "division by zero" twice. If I run it on Python3, it prints "division by zero" in print #1, and then raises a NameError in #2 because 'exc' is not defined.

KDevelop still follows the Python2 scoping in this case, and 'exc' is still highlighted as a use of the variable in the second 'print' call.
Comment 1 Nicolás Alvarez 2016-09-26 03:16:49 UTC
Ugh, this is trickier than I thought because it's not really a "scope". Python pretty much runs 'del exc' after the except block.

exc = "hello world"
try:
    a=1/0
except Exception as exc:
    print(exc)
print(exc)

The second print statement will raise a NameError, it will neither print the exception nor "hello world". So it's not a matter of using a different setup of DUContexts to create a scope; you would need support for deleting individual variables.
Comment 2 Sven Brauch 2016-10-01 18:45:28 UTC
Valid issue, I'll make this a wishlist item though since "del" is not supported at all currently. I guess adding that would go hand in hand with fixing this issue as well.