Python 2.4 output workaround not allowed in try block with finally condition

I am stuck on python2.4, so I cannot use the finally clause with generators or yield . Is there any way around this?

I cannot find any mention of how to get around this limitation in python 2.4, and I am not a big fan of the workarounds I was thinking about (mostly involving __del__ and trying to make sure it was launched in a reasonable amount of time) are not very attractive .

+4
source share
2 answers

You can duplicate code to avoid the finally block:

 try: yield 42 finally: do_something() 

becomes:

 try: yield 42 except: # bare except, catches *anything* do_something() raise # re-raise same exception do_something() 

(I have not tried this on Python 2.4, you may have to look for sys.exc_info instead of re-raise above, as in raise sys.exc_info[0], sys.exc_info[1], sys.exc_info[2] .)

+6
source

The only code that is guaranteed to be called when the generator instance is simply abandoned (garbage collection) is the __del__ methods for its local variables (if references to these objects do not exist externally) and callbacks for weak references to its local variables (the same thing). I recommend a weak reference route because it is non-invasive (you don't need a special class with __del__ - just everything that weakly references). For instance:.

 import weakref def gen(): x = set() def finis(*_): print 'finis!' y = weakref.ref(x, finis) for i in range(99): yield i for i in gen(): if i>5: break 

it prints finis! , If you want to.

+2
source

Source: https://habr.com/ru/post/1302445/


All Articles