how to dispatch objects depending on their class

Peter Otten __peter__ at
Tue Aug 10 17:20:10 CEST 2004

Curzio Basso wrote:

> FUNC = {"<class '__main__.A'>": do_something_with_A,
>          "<class '__main__.B'>": do_something_with_B}
> def func(object):
>    FUNC[type(object)](object)
You'll have to modify that slightly for it to work. It will be very
efficient, too.

func_dict = {A: do_something_with_A, 
             B: do_something_with_B}
def func(obj):

Using classes as keys avoids the ambiguity you fear. The overhead will be
one dictionary lookup and a function call. The main drawback of this simple
approach is that it does not search the inheritance tree but insists on an
exact class match.

> I hope my problem is clear, and excuse me if I am asking about something
> that is common knowledge, but I don't even know what to google for...


python generic dispatch


More information about the Python-list mailing list