实现协议时issubclass检查出现__mro__属性缺失问题求助
issubclass Error When Implementing Iterable Protocol First off, let’s address the most common mistake here—using issubclass() on an instance instead of a class. The issubclass() function expects two class objects as arguments, but if you pass an instance (like issubclass(my_dict_instance, Iterable)), Python will throw a TypeError because it can’t check subclassing against an instance.
To verify if an instance implements the Iterable protocol, use isinstance() instead:
from collections.abc import Iterable my_instance = OrderedKeyDict() print(isinstance(my_instance, Iterable)) # Returns True if your __iter__ is correctly implemented
If you want to check the class itself, make sure you pass the class to issubclass():
print(issubclass(OrderedKeyDict, Iterable)) # Correct class-level check
Why This Happens
The Iterable abstract base class (ABC) uses virtual subclassing via its __subclasshook__ method. This means any class that defines an __iter__ method is automatically considered a subclass of Iterable—you don’t need to explicitly inherit from it. However, this only works when checking against the class (with issubclass) or an instance (with isinstance).
Other Possible Issues
If you’re already using the correct function but still seeing errors, double-check these:
- Your
__iter__method doesn’t return an iterator: The protocol requires__iter__to return an object that implements__next__(and raisesStopIterationwhen exhausted). Usingyieldto return a generator is a simple way to satisfy this:def __iter__(self): for key in self.sorted_keys: yield key # Returns a valid generator iterator - Dynamic method addition: If you added
__iter__to the class after it was defined (instead of in the class body), explicitly register the class withIterable:Iterable.register(OrderedKeyDict)
Example Working Implementation
Here’s a minimal ordered key dictionary that properly implements Iterable:
from collections.abc import Iterable class OrderedKeyDict: def __init__(self): self.data = {} self.key_order = [] def __setitem__(self, key, value): if key not in self.data: self.key_order.append(key) self.data[key] = value def __iter__(self): return iter(self.key_order) # Verify class-level compliance print(issubclass(OrderedKeyDict, Iterable)) # Output: True # Verify instance-level compliance instance = OrderedKeyDict() instance["first"] = 1 instance["second"] = 2 print(isinstance(instance, Iterable)) # Output: True # Test iteration for key in instance: print(key) # Outputs 'first', then 'second'
This should resolve the error you’re encountering. If you can share the full error message, I can refine this further!
内容的提问来源于stack exchange,提问作者nightblade9

