Highlight type hints for non-self attributes

GitOrigin-RevId: 5afecdc4f073bb5ba5a495956fe30985b092634a
This commit is contained in:
Semyon Proshev
2019-07-02 06:52:16 +03:00
committed by intellij-monorepo-bot
parent 5c4eb9b772
commit 58ab6cce3a
2 changed files with 40 additions and 0 deletions
@@ -124,6 +124,12 @@ class PyTypeHintsInspection : PyInspection() {
checkTypeCommentAndParameters(node)
}
override fun visitPyTargetExpression(node: PyTargetExpression) {
super.visitPyTargetExpression(node)
checkAnnotatedNonSelfAttribute(node)
}
private fun checkTypeVarPlacement(call: PyCallExpression, target: PyExpression?) {
if (target == null) {
registerProblem(call, "A 'TypeVar()' expression must always directly be assigned to a variable")
@@ -597,6 +603,23 @@ class PyTypeHintsInspection : PyInspection() {
}
}
private fun checkAnnotatedNonSelfAttribute(node: PyTargetExpression) {
val qualifier = node.qualifier ?: return
if (node.annotation == null && node.typeComment == null) return
val scopeOwner = ScopeUtil.getScopeOwner(node)
if (scopeOwner !is PyFunction) {
registerProblem(node, "Non-self attribute could not be type hinted")
return
}
val self = scopeOwner.parameterList.parameters.firstOrNull()?.takeIf { it.isSelf }
if (self == null ||
PyUtil.multiResolveTopPriority(qualifier, resolveContext).let { it.isNotEmpty() && it.all { e -> e != self }}) {
registerProblem(node, "Non-self attribute could not be type hinted")
}
}
private fun followNotTypingOpaque(target: PyTargetExpression): Boolean {
return !PyTypingTypeProvider.OPAQUE_NAMES.contains(target.qualifiedName)
}
@@ -848,6 +848,23 @@ public class PyTypeHintsInspectionTest extends PyInspectionTestCase {
);
}
public void testAnnotatingNonSelfAttribute() {
runWithLanguageLevel(
LanguageLevel.PYTHON36,
() -> doTestByText("class A:\n" +
" def method(self, b):\n" +
" <warning descr=\"Non-self attribute could not be type hinted\">b.a</warning>: int = 1\n" +
"\n" +
"class B:\n" +
" pass\n" +
"\n" +
"<warning descr=\"Non-self attribute could not be type hinted\">B.a</warning>: str = \"2\"\n" +
"\n" +
"def func(a):\n" +
" <warning descr=\"Non-self attribute could not be type hinted\">a.xxx</warning>: str = \"2\"")
);
}
@NotNull
@Override
protected Class<? extends PyInspection> getInspectionClass() {