'Two Objects Created from the Same Class, isinstance = False

I'm trying to create some unit tests for some code here at work.

The code takes in an object and based on information within that object imports a specific module then creates an instance of it.

The test I am trying to write creates the object and then I check that it is an instance of the class I expect it to import. The issue is the isinstance check is failing.

Here is what my test looks like.

import importlib
from path.to.imported_api import SomeApi

api = importlib.import_module("path.to.imported_api").create_instance()  # create_instance() is a function that returns SomeApi().

assert isinstance(api, SomeApi)  # This returns false, but I am not sure why.


Solution 1:[1]

The reason for the difference is, that whereas both objects refer to the same module, they get different identifiers as you load a new module and bypass sys.modules. See also the explanation here: https://bugs.python.org/issue40427

A hack might be to compare the name:

assert isinstance(api.__class__.__name__, SomeApi.__name__)

Solution 2:[2]

There are a few things that could cause that: So first, it could be that the api is just returning something that looks like SomeApi(). Also it coud is be that SomeApi is overwriting isinstance behaviour.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mortimer R
Solution 2 MegaIng