Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 820719
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T02:31:25+00:00 2026-05-15T02:31:25+00:00

I have code that statically registers (type, handler_function) pairs at module load time, resulting

  • 0

I have code that statically registers (type, handler_function) pairs at module load time, resulting in a dict like this:

HANDLERS = {
  str: HandleStr,
  int: HandleInt,
  ParentClass: HandleCustomParent,
  ChildClass: HandleCustomChild
  }

def HandleObject(obj):
  for data_type in sorted(HANDLERS.keys(), ???):
    if isinstance(obj, data_type):
      HANDLERS[data_type](obj)

Where ChildClass inherits from ParentClass. The problem is that, since its a dict, the order isn’t defined – but how do I introspect type objects to figure out a sort key?

The resulting order should be child classes follow by super classes (most specific types first). E.g. str comes before basestring, and ChildClass comes before ParentClass. If types are unrelated, it doesn’t matter where they go relative to each other.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T02:31:26+00:00Added an answer on May 15, 2026 at 2:31 am

    If you know you’re always dealing with new-style classes:

    def numberofancestors(klass):
        return len(klass.mro())
    

    or, if you worry there may be old-style classes in the mix:

    import inspect
    
    def numberofancestors(klass):
        return len(inspect.getmro(klass))
    

    and then, in either case,

    sorted(HANDLERS, key=numberofancestors, reversed=True)
    

    will give you what you require (you don’t need the .keys() part).

    @Ignacio’s suggestion of a topological sort is theoretically correct, but since, given a class, you can easily and rapidly get the number of its precursors (AKA “ancestors”… in a weird sense of the word whereby you’re one of your ancestors;-), with these numberofancestors functions, my approach is much more practical: it relies on the obvious fact that any derived class has at least one more “ancestor” than any of its bases classes, and therefore, with this key=, it will always sort before any of its bases.

    Unrelated classes may end up in arbitrary order (just like they might in a topological sort), but you’ve made it clear you don’t care about this.

    Edit: the OP, musing in the following comments thread about optimal support for multiple inheritance cases, came up with a drastically different idea than the original one of “pre-sorting” embedded in the question, but his suggestion on how to implement that drastically idea is not optimal:

    [h for h in [HANDLERS.get(c) for c in type(obj).mro()] if h is not None][0]
    

    the idea is good (if multiple-inheritance support is of any interest) but the best implementation thereof would probably be (Python 2.6 or better):

    next(Handlers[c] for c in type(obj).mro() if c in Handlers)
    

    Normally, adict.get(k) and check for not None is faster than if k in adict: adict[k], but this is not a particularly normal case because to use get requires building a “fake” one-item list and “looping” on it to simulate assignment.

    More generally, building a whole list via comprehension just to take its [0]th item is excess work — the next builtin function called on a genexp acts more like a first, as in, “give me the first item of the genexp” and does no extra work beyond that. It raises StopIteration instead of IndexError if the listcomp/genexp is empty, but that’s not normally an issue; you could also have a second argument to next, to be uses as the “default value” if the genexp is empty.

    In 2.5 and earlier you’d have to use (thegenexp).next() instead (and there’s no way to give it a default argument), but while syntactically a tad less shiny it’s more or less equivalent to the 2.6-and-better construct in semantics and speed.

    I’m sure glad the discussion continued in the comments because I think this resulting conclusion is worthwhile and potentially useful (though maybe not in the exact environment of the OP’s application, where multiple inheritance may not in fact be an issue).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 494k
  • Answers 494k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Check here for the docs for the API, and the… May 16, 2026 at 11:04 am
  • Editorial Team
    Editorial Team added an answer Windows itself doesn't make any direct provision for either one,… May 16, 2026 at 11:04 am
  • Editorial Team
    Editorial Team added an answer Put a breakpoint to the line of code you're interested… May 16, 2026 at 11:04 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

I have some code that's written like so: private double function1() { double result2
I noticed that a lot of tutorial instructions often have this code: $sql=SELECT *
I have written some code that makes use of an open source library to
I have code written that converts my Document to a string prior to printing
I have some code that is looking up group memberships from local groups on
I have some code that tries to parse a date string. When I do
I have some code that I want to run in a utility application whenever
I am having a really hard time getting this marshalling down. I have umanaged
I need to code a class that recieves a collection with any number of
I have a piece of C code which with a chunk of memory(static array)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.