[Python] How to fix isinstance failing in pytest when object comes from a different module...

Discussão em 'Python' iniciado por Stack, Julho 3, 2025.

  1. Stack

    Stack Membro Participativo

    If one module returns an instance from another module, isinstance in pytest fails. My directory structure:

    project/
    |--pytest.ini
    |--src/
    |----__init__.py
    |----bar.py
    |----foo.py
    |--test/
    |----test_1.py


    bar.py can return a Bar() instance directly with bar.get_bar() or foo.py can return a Bar() instance created indirectly with foo.get_bar():

    #bar.py
    class Bar:
    pass

    def get_bar():
    return Bar()


    #foo.py
    import bar

    def get_bar():
    return bar.Bar()


    The test below fails on the 2nd isinstance:

    import src.bar
    import src.foo

    def test_1():
    # When the object is supplied by the called module, the type is correct
    bar1 = src.bar.get_bar()
    assert isinstance(bar1, src.bar.Bar)

    # When the object is supplied by another module, the type is incorrect
    bar2 = src.foo.get_bar()
    assert isinstance(bar2, src.bar.Bar)


    This is because bar1 is <src.bar.Bar object at ...> and bar2 is <bar.Bar object at ...>. I can replace isinstance with:

    def same_name(obj_: Any, type_: type) -> bool:
    return obj_.__class__.__name__ == type_.__name__


    but in practice, Bar() is an inherited class and the linter barfs on subsequent uses of Bar(). Is there any way around this?

    Continue reading...

Compartilhe esta Página