Recording a possible use case for lookup_special.
In pytest, we currently discover fixture definitions on an object by iterating dir(obj). Problem is, dir sorts but we want to preserve definition order. We could sort for firstlineno, but that seems slow. So I looked at how dir is implemented, and as far as I can see, it would be possible to implement an order-preserving dir using lookup_special as lookup_special(obj, "__dir__")(). I’m considering using a “polyfill” like this in the meantime, though it’s probably inaccurate and slow in itself, so probably not…
def lookup_special(obj: object, name: str):
cls = type(obj)
for base in cls.__mro__:
if name in base.__dict__:
descriptor = base.__dict__[name]
descriptor_type = type(descriptor)
if hasattr(descriptor_type, "__get__"):
return descriptor_type.__get__(descriptor, obj, cls)
return descriptor
return None
Of course this is a bit of an XY problem, as ideally there would be a dir(obj, sort=False) option, but that seems unlikely.