PY-46546 For Python 3.9+, on "Add type hint for ..." don't import obsolete generic aliases from typing

(cherry picked from commit 7bc7d79e4ad464b67792e19f1be6262946917619)

IJ-CR-149697

GitOrigin-RevId: 5ebc4ec0cf4e5aacffd3f3cd1f62bc5617ae8cf6
This commit is contained in:
Mikhail Golubev
2024-10-16 11:17:43 +03:00
committed by intellij-monorepo-bot
parent 44ee539dbd
commit 1d8c4eebd6
6 changed files with 19 additions and 2 deletions

View File

@@ -300,6 +300,8 @@ public final class PyTypeHintGenerationUtil {
@NotNull TypeEvalContext context,
@NotNull Set<PsiNamedElement> symbols,
@NotNull Set<String> typingTypes) {
boolean useGenericAliasFromTyping =
context.getOrigin() != null && LanguageLevel.forElement(context.getOrigin()).isOlderThan(LanguageLevel.PYTHON39);
if (type == null) {
typingTypes.add("Any");
}
@@ -323,14 +325,14 @@ public final class PyTypeHintGenerationUtil {
if (type instanceof PyCollectionTypeImpl) {
final PyClass pyClass = ((PyCollectionTypeImpl)type).getPyClass();
final String typingCollectionName = PyTypingTypeProvider.TYPING_COLLECTION_CLASSES.get(pyClass.getQualifiedName());
if (typingCollectionName != null && type.isBuiltin()) {
if (typingCollectionName != null && type.isBuiltin() && useGenericAliasFromTyping) {
typingTypes.add(typingCollectionName);
}
else {
symbols.add(pyClass);
}
}
else if (type instanceof PyTupleType) {
else if (type instanceof PyTupleType && useGenericAliasFromTyping) {
typingTypes.add("Tuple");
}
else if (type instanceof PyTypedDictType) {
@@ -356,6 +358,7 @@ public final class PyTypeHintGenerationUtil {
symbols.add(target);
}
}
// TODO in Python 3.9+ use the builtin "type" instead of "typing.Type"
if (type instanceof PyInstantiableType && ((PyInstantiableType<?>)type).isDefinition()) {
typingTypes.add("Type");
}

View File

@@ -0,0 +1 @@
v<caret>ar = [1, 2, 3]

View File

@@ -0,0 +1 @@
var: [list[int]] = [1, 2, 3]

View File

@@ -0,0 +1 @@
var: [tuple[int, int]] = (1, 2)

View File

@@ -279,6 +279,16 @@ public class PyAnnotateVariableTypeIntentionTest extends PyIntentionTestCase {
doAnnotationTest();
}
// PY-46546
public void testAnnotationGenericBuiltinList() {
doTest(LanguageLevel.getLatest());
}
// PY-46546
public void testAnnotationGenericBuiltinTuple() {
doTest(LanguageLevel.getLatest());
}
private void doAnnotationTest() {
doTest(LanguageLevel.PYTHON36);
}