isinstance() unexpectedly returning False

前端 未结 1 2045
[愿得一人]
[愿得一人] 2020-12-06 11:49

I am using the kubernetes python client. In the event that kubernetes isn\'t available when my code starts up, I would like to retry the connection.

When the clie

相关标签:
1条回答
  • 2020-12-06 12:27

    Your code has an indirect dependency on the requests package, and the requests package has a strange submodule called requests.packages. This used to contain copied source code from a number of dependencies, including urllib3, but they stopped doing that. They wanted to keep requests.packages around for backward compatibility, though, so now they're doing something weird.

    Instead of requests.packages including a complete copy of the urllib3 source code, it now imports urllib3 and sets sys.modules['requests.packages.urllib3'] = urllib3. Depending on the requests version, it may set a number of other sys.modules entries, too; for example, as of requests 2.18.4, the source code does

    for package in ('urllib3', 'idna', 'chardet'):
        locals()[package] = __import__(package)
        # This traversal is apparently necessary such that the identities are
        # preserved (requests.packages.urllib3.* is urllib3.*)
        for mod in list(sys.modules):
            if mod == package or mod.startswith(package + '.'):
                sys.modules['requests.packages.' + mod] = sys.modules[mod]
    

    but in 2.17.0, it does

    import urllib3
    sys.modules['requests.packages.urllib3'] = urllib3
    
    import idna
    sys.modules['requests.packages.idna'] = idna
    
    import chardet
    sys.modules['requests.packages.chardet'] = chardet
    

    This code interacts badly with submodules of the imported packages. If some code tries to do import requests.packages.urllib3.exceptions and Python doesn't find a sys.modules['requests.packages.urllib3.exceptions'] entry, Python will recreate the urllib3.exceptions module and set urllib3.exceptions and sys.modules['requests.packages.urllib3.exceptions'] to the new module (but it won't touch sys.modules['urllib3.exceptions']. This will generate new copies of the classes involved, causing your error.

    A related problem with the same cause was reported back in May, leading to the new code shown in 2.18.4. 2.18.4 shouldn't cause the specific problems you're seeing, but it's still fragile, because if any submodules of urllib3 aren't yet loaded at the time requests.packages screws with sys.modules, those submodules will exhibit the same problems you've seen today.

    0 讨论(0)
提交回复
热议问题