[Python-ideas] inspect.getclassdistance

Andrew Barnert abarnert at yahoo.com
Mon Jan 5 17:36:28 CET 2015

On Jan 5, 2015, at 15:05, Alexis Lee <alexisl at hp.com> wrote:

> Andrew Barnert said on Mon, Jan 05, 2015 at 01:09:37PM +0100:
>> On Jan 5, 2015, at 12:20, Alexis Lee <alexisl at hp.com> wrote:
>> You're trying to find out if dst is an ancestor of src (the option of
>> taking a list of pairs, despite being documented, seems to be there
>> only for internal use by recursive calls) and, if so, how long the
>> path is between them.
> All correct.
> (moved for clarity)
>> When would it ever be interesting?
> The usecase is here (comments at line 861, also see 866-894):
>    https://review.openstack.org/#/c/142835/5/nova/api/openstack/compute/servers.py
> IE I receive a NeutronException of some specialised type; based on that
> there are multiple Nova exceptions I might want to throw. I would use
> getclassdistance (or rather, your walker) to sort those and throw the
> first, most-specific exception. EG I might be considering throwing
> either HTTPConflict or HTTPBadRequest, but the former is-a latter, hence
> it's more specific and the one which should be thrown.

I'm afraid I still don't understand the use case. To know that the former is-a latter, all you need is issubclass; what does the distance add?

Maybe you're thinking that, in the case of two unrelated exceptions, the distance from some base class (like Exception) tells you which one is "most specific"? I don't think that's true in general (the hierarchy of Python's standard exceptions and other stdlib exceptions definitely hasn't been designed that way) but maybe your project designed its own exceptions that way on purpose. But if that's true, there ought to be a much simpler option: The "depth" of any exception class is 1 more than the depth of its deepest ancestor, with the root being 0.

Do you actually have a use case where you need to know that exception class A is 2 levels deep from some arbitrary exception class B (as opposed to from the root)?

>> I also don't get why you're using recursion rather than a loop here,
> Just how I think.

Well, if you're you're going to suggest ideas for the Python stdlib, you may want to learn to think Pythonically. Not that recursion is never a good idea in Python, but deliberately using it in place of a for or while loop isn't.

More information about the Python-ideas mailing list