Python Macros
Jeff Shannon
jeff at ccvcorp.com
Tue Oct 5 15:23:17 EDT 2004
Arich Chanachai wrote:
> What if foo doesn't know about bar(), can I tell foo that perhaps it
> should send the bar() message to...say....boo?
In addition to redefining __getattr__()/__setattr__(), as has already
been suggested, it's even easier to have your calling code (which
probably knows more about how to recover from failure than the called
code) decide what to do.
try:
foo.bar()
except AttributeError:
boo.bar()
I'd think that, in most cases, if foo doesn't understand bar(), then it
won't know *why* you're calling bar(), and thus won't be in the best
position to decide what other objects to try bar() on.
To go back to the dog.fetch(cat) example -- if the dog doesn't
understand how to fetch a cat, it probably doesn't know whether a human
would understand how to fetch a cat, either. On the other hand, if
*you* are asking dog to fetch a cat, and the dog doesn't understand,
then you'd be in a good position to decide that the dog's owner might
understand... or that the handy Cat-Fetching Robot (tm) might be a
better choice. The dog can only say "I don't understand, and things I
don't understand go to my owner," while the calling code has a good
chance of having a meaningful fallback plan for each possible situation.
(This sort of setup, with the caller taking responsibility for failure
rather than the callee attempting to make sure that *someone* handles
failure, is far more common in Python than the sort of scheme that
you're asking for.)
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list