Is this considered black magic?

Just van Rossum just at letterror.com
Sun Nov 11 10:25:37 EST 2001


Laura Creighton wrote:

>     for object in object_list:
>         try:
>             object.__class__.__dict__[name_key](object, *args)
>         except KeyError:
>             pass

Besides the tip to use getattr() as others suggested, it's wise to separate
the _getting_ of the method from the _calling_, eg like so:

    for object in object_list:
        try:
            handler = getattr(object, name_key)
        except AttributeError:
            pass
        else:
            handler(*args)

Besides that I find this slightly more readable, there's a very important
difference: it won't mask errors in the *method* anymore. Imagine the method
raises KeyError in your version of the code: to the client code this looks
as if the method didn't exist. This sort of problem can be very awkward to
debug...

Just



More information about the Python-list mailing list