Note that there are some explanatory texts on larger screens.

plurals
  1. POPython method that is also a generator function?
    primarykey
    data
    text
    <p>I'm trying to build a method that also acts like a generator function, at a flip of a switch (<code>want_gen</code> below).</p> <p>Something like:</p> <pre><code>def optimize(x, want_gen): # ... declaration and validation code for i in range(100): # estimate foo, bar, baz # ... some code here x = calculate_next_x(x, foo, bar, baz) if want_gen: yield x if not want_gen: return x </code></pre> <p>But of course this doesn't work -- Python apparently doesn't allow <code>yield</code> and <code>return</code> in the same method, even though they cannot be executed simultaneously. </p> <p>The code is quite involved, and refactoring the declaration and validation code doesn't make much sense (too many state variables -- I will end up with difficult-to-name helper routines of 7+ parameters, which is decidedly ugly). And of course, I'd like to avoid code duplication as much as possible.</p> <p>Is there some code pattern that would make sense here to achieve the behaviour I want?</p> <hr> <p>Why do I need that?</p> <p>I have a rather complicated and time-consuming optimization routine, and I'd like to get feedback about its current state during runtime (to display in e.g. GUI). The old behaviour needs to be there for backwards compatibility. Multithreading and messaging is too much work for too little additional benefit, especially when cross-platform operation is necessary.</p> <p><strong>Edit:</strong> Perhaps I should have mentioned that since each optimization step is rather lengthy (there are some numerical simulations involved as well), I'd like to be able to "step in" at a certain iteration and twiddle some parameters, or abort the whole business altogether. The generators seemed like a good idea, since I could launch another iteration at my discretion, fiddling in the meantime with some parameters.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload