Testing types with issubclass returns inconsistent results

Viewed 81

I have a class A with no attributes, which I test to see if it is a subclass of typing.Container. That test fails, as expected.

In a separate test I add the __contains(self, k)__ attribute to A, and test to see if it is a subclass of typing.Container, and that test passes.

Now the weird thing is if I test whether A is a subclass of typing.Conainer, and then add the __contains(self, k)__ attribute, and then again test whether A is a subclass of typing.Container, that test fails.

What is happening that causes the last test to fail, even when A does have the attribute __contains__(self, k)__?

import pytest
from typing import Container

@pytest.fixture
def A():
    class A:...
    return A

def test_notsubclass(A):
    # passes
    assert not issubclass(A, Container)

def test_addcontains(A):
    # passes
    def __contains__(self, k): ...
    setattr(A, '__contains__', __contains__)
    assert issubclass(A, Container)

def test_first_then_add_contains(A):
    # passes
    assert not issubclass(A, Container)
    def __contains__(self, k): ...
    setattr(A, '__contains__', __contains__)

    # fails
    assert issubclass(A, Container)
1 Answers
Related