Timmmm
Timmmm

Reputation: 96546

Python isinstance returns false for types with the same ID

I am having a strange issue with this code in cpuset. For some reason isinstance('/user', str) is returning False. I added some logging like this:

    log.debug("repr(name): %s", repr(name))
    log.debug("type(name): %s", type(name))
    log.debug("name.__class__: %s", name.__class__)
    log.debug("id(name.__class__): %s", str(id(name.__class__)))
    log.debug("id(''.__class__): %s", str(id("".__class__)))
    log.debug("isinstance(name, str)?: %s", str(isinstance(name, str)))

Here is the result.

180820-14:28:55 set    DEBUG    repr(name): '/user'
180820-14:28:55 set    DEBUG    type(name): <type 'str'>
180820-14:28:55 set    DEBUG    name.__class__: <type 'str'>
180820-14:28:55 set    DEBUG    id(name.__class__): 94668708986528
180820-14:28:55 set    DEBUG    id(''.__class__): 94668708986528
180820-14:28:55 set    DEBUG    isinstance(name, str)?: False

Pretty WTF I'd say. What is going on here?

Upvotes: 0

Views: 358

Answers (1)

Timmmm
Timmmm

Reputation: 96546

Aha! I think it is because they have:

from builtins import str

Apparently this is to get a Python 3 like string. But... it is pretty messed up.

>>> from builtins import str
>>> isinstance("foo", str)
False

I guess that's what you get if you refuse to move to Python 3.

Upvotes: 1

Related Questions