On Fri, Mar 20, 2009 at 2:09 AM, <el...@cmbi.ru.nl> wrote: > On Mar 20, 9:44 am, Chris Rebert <c...@rebertia.com> wrote: >> On Fri, Mar 20, 2009 at 1:32 AM, <el...@cmbi.ru.nl> wrote: >> > Hi everyone, >> >> > is there a sufficiently easy possibility for a Python function to find >> > out whether it has been called from a try-block or not? >> >> > try: >> > print "Calling foo" >> > foo() >> > except: >> > print "Got exception" >> >> > In the example above, foo() should be able to 'see' that it was called >> > from a try block, allowing it to behave differently. >> >> > Can this information be obtained from the traceback/frame/code >> > objects, or is that too difficult? >> >> It might be possible, but it seems like there ought to be a better way >> to accomplish your goal. Could you explain why you want to do this in >> the first place? Perhaps a better alternative can be found. > > Well, foo() communicates with another application using sockets, and > an exception might occur in the other application. For performance > reasons, foo() normally returns before the other application has > finished execution, unless foo() is forced to wait for the result. > This can for example be achieved by using foo()'s return value (foo() > uses self-inspection to see if its return value is discarded or not). > > I also want foo() to wait in case it's in a try block, so that the > user can catch exceptions that occur in the other application.
Is there any reason you can't just add a parameter (e.g. 'wait') to foo() to tell it whether to wait for the exception or not? It's certainly less magical than detecting `try` in the caller. Cheers, Chris -- I have a blog: http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list