-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Python: Modernize Unexpected Raise In Special Method query #20120
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
Merged
joefarebrother
merged 13 commits into
github:main
from
joefarebrother:python-qual-unexpected-raise-special
Aug 27, 2025
Merged
Changes from 12 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
73d257e
Port unexpected raise away from pointsto
joefarebrother b973806
try excluding set methods, add methods, update alert messages
joefarebrother b9f6657
Remove use of toString. This does also reduce reaults from cases wher…
joefarebrother 362bfba
Update unit tests
joefarebrother 871688f
Update docs
joefarebrother 3525e83
Add changenote + some doc updates
joefarebrother 8bdf680
Add qldoc
joefarebrother 9af2ab8
Cleanups
joefarebrother d7b855c
qhelp fix
joefarebrother 958fddb
cleanup order and remove duplicates for arithmetic methods
joefarebrother c0da9c4
Fix typo in test dir name + update examples
joefarebrother d8083ad
Doc updates
joefarebrother 5b0beb9
Update python/ql/src/Functions/IncorrectRaiseInSpecialMethod.qhelp
joefarebrother File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,114 +7,188 @@ | |
| * error-handling | ||
| * @problem.severity recommendation | ||
| * @sub-severity high | ||
| * @precision very-high | ||
| * @precision high | ||
| * @id py/unexpected-raise-in-special-method | ||
| */ | ||
|
|
||
| import python | ||
| import semmle.python.ApiGraphs | ||
| import semmle.python.dataflow.new.internal.DataFlowDispatch | ||
|
|
||
| private predicate attribute_method(string name) { | ||
| name = "__getattribute__" or name = "__getattr__" or name = "__setattr__" | ||
| /** Holds if `name` is the name of a special method for attribute access such as `a.b`, that should raise an `AttributeError`. */ | ||
| private predicate attributeMethod(string name) { | ||
| name = ["__getattribute__", "__getattr__", "__delattr__"] // __setattr__ excluded as it makes sense to raise different kinds of errors based on the `value` parameter | ||
| } | ||
|
|
||
| private predicate indexing_method(string name) { | ||
| name = "__getitem__" or name = "__setitem__" or name = "__delitem__" | ||
| /** Holds if `name` is the name of a special method for indexing operations such as `a[b]`, that should raise a `LookupError`. */ | ||
| private predicate indexingMethod(string name) { | ||
| name = ["__getitem__", "__delitem__"] // __setitem__ excluded as it makes sense to raise different kinds of errors based on the `value` parameter | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thank you for adding these comments! ❤️ |
||
| } | ||
|
|
||
| private predicate arithmetic_method(string name) { | ||
| name in [ | ||
| "__add__", "__sub__", "__or__", "__xor__", "__rshift__", "__pow__", "__mul__", "__neg__", | ||
| "__radd__", "__rsub__", "__rdiv__", "__rfloordiv__", "__div__", "__rdiv__", "__rlshift__", | ||
| "__rand__", "__ror__", "__rxor__", "__rrshift__", "__rpow__", "__rmul__", "__truediv__", | ||
| "__rtruediv__", "__pos__", "__iadd__", "__isub__", "__idiv__", "__ifloordiv__", "__idiv__", | ||
| "__ilshift__", "__iand__", "__ior__", "__ixor__", "__irshift__", "__abs__", "__ipow__", | ||
| "__imul__", "__itruediv__", "__floordiv__", "__div__", "__divmod__", "__lshift__", "__and__" | ||
| /** Holds if `name` is the name of a special method for arithmetic operations. */ | ||
| private predicate arithmeticMethod(string name) { | ||
| name = | ||
|
||
| [ | ||
| "__add__", "__sub__", "__and__", "__or__", "__xor__", "__lshift__", "__rshift__", "__pow__", | ||
| "__mul__", "__div__", "__divmod__", "__truediv__", "__floordiv__", "__matmul__", "__radd__", | ||
| "__rsub__", "__rand__", "__ror__", "__rxor__", "__rlshift__", "__rrshift__", "__rpow__", | ||
| "__rmul__", "__rdiv__", "__rdivmod__", "__rtruediv__", "__rfloordiv__", "__rmatmul__", | ||
| "__iadd__", "__isub__", "__iand__", "__ior__", "__ixor__", "__ilshift__", "__irshift__", | ||
| "__ipow__", "__imul__", "__idiv__", "__idivmod__", "__itruediv__", "__ifloordiv__", | ||
| "__imatmul__", "__pos__", "__neg__", "__abs__", "__invert__", | ||
| ] | ||
| } | ||
|
|
||
| private predicate ordering_method(string name) { | ||
| name = "__lt__" | ||
| or | ||
| name = "__le__" | ||
| or | ||
| name = "__gt__" | ||
| or | ||
| name = "__ge__" | ||
| or | ||
| name = "__cmp__" and major_version() = 2 | ||
| /** Holds if `name is the name of a special method for ordering operations such as `a < b`. */ | ||
| private predicate orderingMethod(string name) { | ||
| name = | ||
| [ | ||
| "__lt__", | ||
| "__le__", | ||
| "__gt__", | ||
| "__ge__", | ||
| ] | ||
| } | ||
|
|
||
| private predicate cast_method(string name) { | ||
| name = "__nonzero__" and major_version() = 2 | ||
| or | ||
| name = "__int__" | ||
| or | ||
| name = "__float__" | ||
| or | ||
| name = "__long__" | ||
| or | ||
| name = "__trunc__" | ||
| or | ||
| name = "__complex__" | ||
| /** Holds if `name` is the name of a special method for casting an object to a numeric type, such as `int(x)` */ | ||
| private predicate castMethod(string name) { | ||
| name = | ||
| [ | ||
| "__int__", | ||
| "__float__", | ||
| "__index__", | ||
| "__trunc__", | ||
| "__complex__" | ||
| ] // __bool__ excluded as it makes sense to allow it to always raise | ||
| } | ||
|
|
||
| predicate correct_raise(string name, ClassObject ex) { | ||
| ex.getAnImproperSuperType() = theTypeErrorType() and | ||
| /** Holds if we allow a special method named `name` to raise `exec` as an exception. */ | ||
| predicate correctRaise(string name, Expr exec) { | ||
| execIsOfType(exec, "TypeError") and | ||
| ( | ||
| name = "__copy__" or | ||
| name = "__deepcopy__" or | ||
| name = "__call__" or | ||
| indexing_method(name) or | ||
| attribute_method(name) | ||
| indexingMethod(name) or | ||
| attributeMethod(name) or | ||
| // Allow add methods to raise a TypeError, as they can be used for sequence concatenation as well as arithmetic | ||
| name = ["__add__", "__iadd__", "__radd__"] | ||
| ) | ||
| or | ||
| preferred_raise(name, ex) | ||
| or | ||
| preferred_raise(name, ex.getASuperType()) | ||
| exists(string execName | | ||
| preferredRaise(name, execName, _) and | ||
| execIsOfType(exec, execName) | ||
| ) | ||
| } | ||
|
|
||
| predicate preferred_raise(string name, ClassObject ex) { | ||
| attribute_method(name) and ex = theAttributeErrorType() | ||
| or | ||
| indexing_method(name) and ex = Object::builtin("LookupError") | ||
| or | ||
| ordering_method(name) and ex = theTypeErrorType() | ||
| or | ||
| arithmetic_method(name) and ex = Object::builtin("ArithmeticError") | ||
| or | ||
| name = "__bool__" and ex = theTypeErrorType() | ||
| /** Holds if it is preferred for `name` to raise exceptions of type `execName`. `message` is the alert message. */ | ||
| predicate preferredRaise(string name, string execName, string message) { | ||
| attributeMethod(name) and | ||
| execName = "AttributeError" and | ||
| message = "should raise an AttributeError instead." | ||
| or | ||
| indexingMethod(name) and | ||
| execName = "LookupError" and | ||
| message = "should raise a LookupError (KeyError or IndexError) instead." | ||
| or | ||
| orderingMethod(name) and | ||
| execName = "TypeError" and | ||
| message = "should raise a TypeError or return NotImplemented instead." | ||
| or | ||
| arithmeticMethod(name) and | ||
| execName = "ArithmeticError" and | ||
| message = "should raise an ArithmeticError or return NotImplemented instead." | ||
| or | ||
| name = "__bool__" and | ||
| execName = "TypeError" and | ||
| message = "should raise a TypeError instead." | ||
| } | ||
|
|
||
| predicate no_need_to_raise(string name, string message) { | ||
| name = "__hash__" and message = "use __hash__ = None instead" | ||
| or | ||
| cast_method(name) and message = "there is no need to implement the method at all." | ||
| /** Holds if `exec` is an exception object of the type named `execName`. */ | ||
| predicate execIsOfType(Expr exec, string execName) { | ||
| // Might make sense to have execName be an IPA type here. Or part of a more general API modeling builtin/stdlib subclass relations. | ||
| exists(string subclass | | ||
| execName = "TypeError" and | ||
| subclass = "TypeError" | ||
| or | ||
| execName = "LookupError" and | ||
| subclass = ["LookupError", "KeyError", "IndexError"] | ||
| or | ||
| execName = "ArithmeticError" and | ||
| subclass = ["ArithmeticError", "FloatingPointError", "OverflowError", "ZeroDivisionError"] | ||
| or | ||
| execName = "AttributeError" and | ||
| subclass = "AttributeError" | ||
| | | ||
| exec = API::builtin(subclass).getACall().asExpr() | ||
| or | ||
| exec = API::builtin(subclass).getASubclass().getACall().asExpr() | ||
| ) | ||
| } | ||
|
|
||
| /** | ||
| * Holds if `meth` need not be implemented if it always raises. `message` is the alert message, and `allowNotImplemented` is true | ||
| * if we still allow the method to always raise `NotImplementedError`. | ||
| */ | ||
| predicate noNeedToAlwaysRaise(Function meth, string message, boolean allowNotImplemented) { | ||
| meth.getName() = "__hash__" and | ||
| message = "use __hash__ = None instead." and | ||
| allowNotImplemented = false | ||
| or | ||
| castMethod(meth.getName()) and | ||
| message = "this method does not need to be implemented." and | ||
| allowNotImplemented = true and | ||
| // Allow an always raising cast method if it's overriding other behavior | ||
| not exists(Function overridden | | ||
| overridden.getName() = meth.getName() and | ||
| overridden.getScope() = getADirectSuperclass+(meth.getScope()) and | ||
| not alwaysRaises(overridden, _) | ||
| ) | ||
| } | ||
|
|
||
| /** Holds if `func` has a decorator likely marking it as an abstract method. */ | ||
| predicate isAbstract(Function func) { func.getADecorator().(Name).getId().matches("%abstract%") } | ||
|
|
||
| /** Holds if `f` always raises the exception `exec`. */ | ||
| predicate alwaysRaises(Function f, Expr exec) { | ||
| directlyRaises(f, exec) and | ||
| strictcount(Expr e | directlyRaises(f, e)) = 1 and | ||
| not exists(f.getANormalExit()) | ||
| } | ||
|
|
||
| predicate is_abstract(FunctionObject func) { | ||
| func.getFunction().getADecorator().(Name).getId().matches("%abstract%") | ||
| /** Holds if `f` directly raises `exec` using a `raise` statement. */ | ||
| predicate directlyRaises(Function f, Expr exec) { | ||
|
||
| exists(Raise r | | ||
| r.getScope() = f and | ||
| exec = r.getException() and | ||
| exec instanceof Call | ||
| ) | ||
| } | ||
|
|
||
| predicate always_raises(FunctionObject f, ClassObject ex) { | ||
| ex = f.getARaisedType() and | ||
| strictcount(f.getARaisedType()) = 1 and | ||
| not exists(f.getFunction().getANormalExit()) and | ||
| /* raising StopIteration is equivalent to a return in a generator */ | ||
| not ex = theStopIterationType() | ||
| /** Holds if `exec` is a `NotImplementedError`. */ | ||
| predicate isNotImplementedError(Expr exec) { | ||
| exec = API::builtin("NotImplementedError").getACall().asExpr() | ||
| } | ||
|
|
||
| from FunctionObject f, ClassObject cls, string message | ||
| /** Gets the name of the builtin exception type `exec` constructs, if it can be determined. */ | ||
| string getExecName(Expr exec) { result = exec.(Call).getFunc().(Name).getId() } | ||
|
|
||
| from Function f, Expr exec, string message | ||
| where | ||
| f.getFunction().isSpecialMethod() and | ||
| not is_abstract(f) and | ||
| always_raises(f, cls) and | ||
| f.isSpecialMethod() and | ||
| not isAbstract(f) and | ||
| directlyRaises(f, exec) and | ||
| ( | ||
| no_need_to_raise(f.getName(), message) and not cls.getName() = "NotImplementedError" | ||
| exists(boolean allowNotImplemented, string subMessage | | ||
| alwaysRaises(f, exec) and | ||
| noNeedToAlwaysRaise(f, subMessage, allowNotImplemented) and | ||
| (allowNotImplemented = true implies not isNotImplementedError(exec)) and // don't alert if it's a NotImplementedError and that's ok | ||
| message = "This method always raises $@ - " + subMessage | ||
| ) | ||
| or | ||
| not correct_raise(f.getName(), cls) and | ||
| not cls.getName() = "NotImplementedError" and | ||
| exists(ClassObject preferred | preferred_raise(f.getName(), preferred) | | ||
| message = "raise " + preferred.getName() + " instead" | ||
| not isNotImplementedError(exec) and | ||
| not correctRaise(f.getName(), exec) and | ||
| exists(string subMessage | preferredRaise(f.getName(), _, subMessage) | | ||
| if alwaysRaises(f, exec) | ||
| then message = "This method always raises $@ - " + subMessage | ||
| else message = "This method raises $@ - " + subMessage | ||
| ) | ||
| ) | ||
| select f, "Function always raises $@; " + message, cls, cls.toString() | ||
| select f, message, exec, getExecName(exec) | ||
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.