Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions packages/pyright-internal/src/analyzer/typeEvaluator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3402,9 +3402,22 @@ export function createTypeEvaluator(
const iterReturnType = getTypeOfMagicMethodCall(subtype, iterMethodName, [], errorNode)?.type;

if (!iterReturnType) {
// There was no __iter__. See if we can fall back to
// the __getitem__ method instead.
// There was no callable __iter__. The legacy sequence protocol
// falls back to __getitem__, but CPython does that only when
// __iter__ is missing. An explicit `__iter__ = None` (or any
// non-callable __iter__) makes the object not iterable.
let hasExplicitIterMember = false;
if (!isAsync && isClassInstance(subtype)) {
hasExplicitIterMember = !!lookUpObjectMember(
subtype,
iterMethodName,
MemberAccessFlags.SkipInstanceMembers |
MemberAccessFlags.SkipAttributeAccessOverride |
MemberAccessFlags.SkipObjectBaseClass
);
Comment thread
rchiodo marked this conversation as resolved.
}

if (!isAsync && isClassInstance(subtype) && !hasExplicitIterMember) {
const getItemReturnType = getTypeOfMagicMethodCall(
subtype,
'__getitem__',
Expand Down
44 changes: 44 additions & 0 deletions packages/pyright-internal/src/tests/samples/forLoop3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# This sample tests that `__iter__ = None` disables iteration even
# when `__getitem__` is defined. CPython raises TypeError in this case.


class SequenceProtocol:
def __getitem__(self, item: int) -> int:
if item >= 3:
raise IndexError
return item


# The legacy sequence protocol should still be iterable.
for _ in SequenceProtocol():
pass


class IterNone:
def __getitem__(self, item: int) -> int:
return item

__iter__ = None


# This should generate an error because __iter__ is None.
for _ in IterNone():
pass


class IterNoneSubclass(IterNone):
pass


# This should generate an error because __iter__ is None.
for _ in IterNoneSubclass():
pass


class IterRestored(IterNone):
def __iter__(self):
yield 1


for _ in IterRestored():
pass
6 changes: 6 additions & 0 deletions packages/pyright-internal/src/tests/typeEvaluator3.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,12 @@ test('ForLoop2', () => {
TestUtils.validateResults(analysisResults, 7);
});

test('ForLoop3', () => {
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['forLoop3.py']);

TestUtils.validateResults(analysisResults, 2);
});

test('Comprehension1', () => {
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['comprehension1.py']);

Expand Down
Loading