Top-rated recipes tagged "generator"http://code.activestate.com/recipes/tags/generator/top/2016-03-18T19:11:48-07:00ActiveState Code RecipesRun asynchronous tasks using coroutines (Python)
2010-08-06T16:16:20-07:00Arnau Sanchezhttp://code.activestate.com/recipes/users/4173270/http://code.activestate.com/recipes/577129-run-asynchronous-tasks-using-coroutines/
<p style="color: grey">
Python
recipe 577129
by <a href="/recipes/users/4173270/">Arnau Sanchez</a>
(<a href="/recipes/tags/coroutine/">coroutine</a>, <a href="/recipes/tags/event/">event</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/gobject/">gobject</a>, <a href="/recipes/tags/gtk/">gtk</a>, <a href="/recipes/tags/gui/">gui</a>, <a href="/recipes/tags/network/">network</a>, <a href="/recipes/tags/nonblocking/">nonblocking</a>, <a href="/recipes/tags/pygtk/">pygtk</a>).
Revision 20.
</p>
<p>This recipe shows a simple, transparent (and hopefully pythonic) way of running asynchronous tasks when writing a event-driven application (i.e. GUI). The aim is to allow a programmer to write time-consuming functions (usually IO-bound, but not only) with sequential-looking code, instead of scattering the logic over a bunch of callbacks. We will take advantage of the coroutines introduced in Python 2.5 (see <a href="http://www.python.org/dev/peps/pep-0342" rel="nofollow">http://www.python.org/dev/peps/pep-0342</a>). </p>
<p>The goal: wouldn't it be great if we could write something like this?</p>
<pre class="prettyprint"><code>def myjob(entry, arg1, arg2, arg3):
result1 = function_that_takes_eons_to_complete(arg1, arg2)
result2 = another_function_that_downloads_a_big_really_big_file(result1, arg3)
entry.set_text("The result is: %d" % result2)
def on_start_button___clicked(button, entry):
myjob(entry, 1, 2, 3)
...
gtk.main()
</code></pre>
<p>Indeed, but we can't! The GUI will hang until the job is done and the user will be rightfully angry. Coroutines to the rescue: the absolute minimal change we can make to this code is transforming <em>myjob</em> into a coroutine and yield every time we do blocking stuff:</p>
<pre class="prettyprint"><code>def myjob(entry, arg1, arg2, arg3):
result1 = yield some_task(arg1, arg2)
result2 = yield some_other_task(result1, arg3)
entry.set_text("The result is: %d" % result2)
def on_start__clicked(button, entry):
start_job(myjob(entry, 1, 2, 3))
</code></pre>
<p><em>some_task</em> and <em>some_other_task</em> are here the asynchronous implementation of the sequential tasks used in the first fragment, and <em>start_job</em> the wrapper around the coroutine. Note that we still have to implement non-blocking versions of the tasks, but they are usually pretty generic (wait some time, download a file, ...) and can be re-used. If you happen to have a CPU-bound function or even a IO-bound code you cannot split (<em>urllib2</em> anyone?), you can always use a generic threaded task (granted, the whole point of using co-routines should be avoiding threads, but there is no alternative here).</p>
<p>At the end, all the plumbing we need to make it work is just 1 function: <em>start_job</em> (wrapper around the job to manage the flow of the coroutine). The rest of the code -two asynchronous tasks (<em>sleep_task</em>, <em>threaded_task</em>) and a demo app- are shown solely as an example.</p>
Wrap any iterable context manager so it closes when consumed (Python)
2012-11-19T20:10:35-08:00Andrew Barnerthttp://code.activestate.com/recipes/users/4184316/http://code.activestate.com/recipes/578342-wrap-any-iterable-context-manager-so-it-closes-whe/
<p style="color: grey">
Python
recipe 578342
by <a href="/recipes/users/4184316/">Andrew Barnert</a>
(<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/context_manager/">context_manager</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/iterable/">iterable</a>, <a href="/recipes/tags/iterator/">iterator</a>, <a href="/recipes/tags/with_statement/">with_statement</a>).
</p>
<p>There are a few types in Python—most notably, files—that are both iterators and context managers. For trivial cases, these features are easy to use together, but as soon as you need to use the iterator lazily or asynchronously, a with statement won't help. That's where this recipe comes in handy:</p>
<pre class="prettyprint"><code>send_async(with_iter(open(path, 'r')))
</code></pre>
<p>This also allows you to "forward" closing for a wrapped iterator, so closing the outer iterator also closes the inner one:</p>
<pre class="prettyprint"><code>sync_async(line.upper() for line in with_iter(open(path, 'r')))
</code></pre>
Left-handed password generator (Python)
2011-10-31T12:51:14-07:00Alexhttp://code.activestate.com/recipes/users/4179771/http://code.activestate.com/recipes/577930-left-handed-password-generator/
<p style="color: grey">
Python
recipe 577930
by <a href="/recipes/users/4179771/">Alex</a>
(<a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/lefthand/">lefthand</a>, <a href="/recipes/tags/lefthanded/">lefthanded</a>, <a href="/recipes/tags/password/">password</a>, <a href="/recipes/tags/passwords/">passwords</a>).
Revision 2.
</p>
<p>Generate passwords that can easily be typed with only the left hand, very simple script</p>
Retry loop (Python)
2013-05-23T20:45:01-07:00Ryan Nowakowskihttp://code.activestate.com/recipes/users/4186624/http://code.activestate.com/recipes/578527-retry-loop/
<p style="color: grey">
Python
recipe 578527
by <a href="/recipes/users/4186624/">Ryan Nowakowski</a>
(<a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/loop/">loop</a>, <a href="/recipes/tags/retry/">retry</a>, <a href="/recipes/tags/timeout/">timeout</a>).
</p>
<p>Encapsulates the logic of a retry loop using a generator function.</p>
Asynchronous subprocess using asyncore (Python)
2013-01-21T19:51:00-08:00Glenn Eychanerhttp://code.activestate.com/recipes/users/4172294/http://code.activestate.com/recipes/576957-asynchronous-subprocess-using-asyncore/
<p style="color: grey">
Python
recipe 576957
by <a href="/recipes/users/4172294/">Glenn Eychaner</a>
(<a href="/recipes/tags/async/">async</a>, <a href="/recipes/tags/asynchronous/">asynchronous</a>, <a href="/recipes/tags/asyncore/">asyncore</a>, <a href="/recipes/tags/coroutine/">coroutine</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/ipc/">ipc</a>, <a href="/recipes/tags/subprocess/">subprocess</a>).
Revision 21.
</p>
<p>A coroutine-based wrapper for subprocess.Popen that uses asyncore to communicate with child processes asynchronously. This allows subprocesses to be called from within socket servers or clients without needing a complicated event loop to check both. Uses <a href="http://code.activestate.com/recipes/576965/">recipe 576965</a> to provide the asynchronous coroutine framework, <a href="http://code.activestate.com/recipes/576967/">recipe 576967</a> to provide asynchronous pipes, and <a href="http://code.activestate.com/recipes/577600/">recipe 577600</a> to provide multiple alarms.</p>
Run async code inline, nonblocking (Python)
2009-11-11T12:55:01-08:00Thomas Ahlehttp://code.activestate.com/recipes/users/4060075/http://code.activestate.com/recipes/576952-run-async-code-inline-nonblocking/
<p style="color: grey">
Python
recipe 576952
by <a href="/recipes/users/4060075/">Thomas Ahle</a>
(<a href="/recipes/tags/asynchronous/">asynchronous</a>, <a href="/recipes/tags/closure/">closure</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/threads/">threads</a>).
Revision 7.
</p>
<p>A decorator, that makes it easy to switch between the mainthread and background threads.</p>
Python Short URL Generator (Python)
2014-11-09T11:19:07-08:00Des Wagnerhttp://code.activestate.com/recipes/users/4191097/http://code.activestate.com/recipes/578961-python-short-url-generator/
<p style="color: grey">
Python
recipe 578961
by <a href="/recipes/users/4191097/">Des Wagner</a>
(<a href="/recipes/tags/deterministic/">deterministic</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/short/">short</a>, <a href="/recipes/tags/tiny/">tiny</a>, <a href="/recipes/tags/unique/">unique</a>, <a href="/recipes/tags/url/">url</a>).
</p>
<p>Python implementation for generating Tiny URL- and bit.ly-like URLs.</p>
And yet another round-robin generator (Python)
2013-11-13T19:30:29-08:00Jan Müllerhttp://code.activestate.com/recipes/users/4183984/http://code.activestate.com/recipes/578768-and-yet-another-round-robin-generator/
<p style="color: grey">
Python
recipe 578768
by <a href="/recipes/users/4183984/">Jan Müller</a>
(<a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/itertools/">itertools</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/roundrobin/">roundrobin</a>).
</p>
<p>I know that there is a <a href="http://code.activestate.com/recipes/528936-roundrobin-generator/">nice recipe</a> already that even made it into the <a href="http://docs.python.org/2/library/itertools.html">Python documentation</a>, but this one is more concise and at the same time simpler.</p>
<pre class="prettyprint"><code>>>> list(roundrobin('ABC', 'D', 'EF'))
['A', 'D', 'E', 'B', 'F', 'C']
</code></pre>
Retry loop (Python)
2013-05-24T05:19:50-07:00Oren Tiroshhttp://code.activestate.com/recipes/users/2033964/http://code.activestate.com/recipes/578163-retry-loop/
<p style="color: grey">
Python
recipe 578163
by <a href="/recipes/users/2033964/">Oren Tirosh</a>
(<a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/loop/">loop</a>, <a href="/recipes/tags/retry/">retry</a>, <a href="/recipes/tags/timeout/">timeout</a>).
Revision 4.
</p>
<p>Encapsulates the logic of a retry loop using a generator function.</p>
Password Generator (Python)
2011-10-14T13:35:21-07:00Alexander Thomas Cruzhttp://code.activestate.com/recipes/users/4179528/http://code.activestate.com/recipes/577905-password-generator/
<p style="color: grey">
Python
recipe 577905
by <a href="/recipes/users/4179528/">Alexander Thomas Cruz</a>
(<a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/password/">password</a>, <a href="/recipes/tags/randomization/">randomization</a>).
Revision 4.
</p>
<p>Generates a really strong and secure password. It uses multiple characters and symbols. Remember to score please! It really means a lot to me. Revision 4 includes an input so you can choose how many characters you want your password to have. It is also faster due to a suggestion by Garel Alex. Thanks!</p>
Configurable password generator/checker (Python)
2008-11-10T01:50:54-08:00Dario Lopez-Kästenhttp://code.activestate.com/recipes/users/4167913/http://code.activestate.com/recipes/576561-configurable-password-generatorchecker/
<p style="color: grey">
Python
recipe 576561
by <a href="/recipes/users/4167913/">Dario Lopez-Kästen</a>
(<a href="/recipes/tags/checker/">checker</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/pasword/">pasword</a>, <a href="/recipes/tags/policy/">policy</a>).
Revision 2.
</p>
<p>Yet another password generator module. This module contains utility functions for both generating and checking passwords in accordance to a (policy).</p>
<p>Default Password Properties Policy:</p>
<ul>
<li>Minimum Password lenght is 8 tokens</li>
<li>At least four unique tokens</li>
<li>At least four character tokens</li>
<li>At least one number token</li>
<li>At least one special character token</li>
</ul>
grep in Python (Python)
2014-03-05T19:47:50-08:00Andy Dustmanhttp://code.activestate.com/recipes/users/2435929/http://code.activestate.com/recipes/578845-grep-in-python/
<p style="color: grey">
Python
recipe 578845
by <a href="/recipes/users/2435929/">Andy Dustman</a>
(<a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/grep/">grep</a>, <a href="/recipes/tags/search/">search</a>).
</p>
<p>The grep() function is inspired by UNIX grep, but is not limited to string patterns and files or streams.</p>
Yet Another Python Generator... (Python)
2011-12-19T08:14:55-08:00Barry Walkerhttp://code.activestate.com/recipes/users/4177147/http://code.activestate.com/recipes/577990-yet-another-python-generator/
<p style="color: grey">
Python
recipe 577990
by <a href="/recipes/users/4177147/">Barry Walker</a>
(<a href="/recipes/tags/audio/">audio</a>, <a href="/recipes/tags/demo/">demo</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/linux/">linux</a>, <a href="/recipes/tags/signal/">signal</a>, <a href="/recipes/tags/sound/">sound</a>, <a href="/recipes/tags/source/">source</a>, <a href="/recipes/tags/sweep/">sweep</a>).
</p>
<p>Aha, but not what big guns were expecting...</p>
<p>LF Audio Sweep Generator.</p>
<p>Another kids level project to do for yourselves...</p>
<p>This is a Python DEMO to show the power of the sound card using Linux to
generate an Audio Sweep Signal from 4KHz down to 100Hz and back again.</p>
<p>Written in such a way that anyone can understand how it works...
This is for Linux and Python 2.x.x. Read the code for much more information, and......
A Python 3.x.x version is here:-</p>
<p><a href="http://www.linuxformat.com/forums/viewtopic.php?t=14411" rel="nofollow">http://www.linuxformat.com/forums/viewtopic.php?t=14411</a></p>
<p>Enjoy finding simple solutions to often VERY difficult problems...</p>
<p>Bazza, G0LCU...</p>
Random Passwords (Python)
2010-07-27T20:28:17-07:00Danillo Souzahttp://code.activestate.com/recipes/users/4174445/http://code.activestate.com/recipes/577339-random-passwords/
<p style="color: grey">
Python
recipe 577339
by <a href="/recipes/users/4174445/">Danillo Souza</a>
(<a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/password/">password</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/random/">random</a>).
</p>
<p>Generate strong random passwords of specified length.</p>
Windowing an iterable with itertools (Python)
2010-04-15T18:45:41-07:00Daniel Cohnhttp://code.activestate.com/recipes/users/4172918/http://code.activestate.com/recipes/577196-windowing-an-iterable-with-itertools/
<p style="color: grey">
Python
recipe 577196
by <a href="/recipes/users/4172918/">Daniel Cohn</a>
(<a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/iterable/">iterable</a>, <a href="/recipes/tags/iterator/">iterator</a>, <a href="/recipes/tags/loop/">loop</a>, <a href="/recipes/tags/peeking/">peeking</a>, <a href="/recipes/tags/window/">window</a>).
</p>
<p>Oftentimes a programmer needs to peek into an iterator without advancing it, a task for which many good solutions already exist. But what if the intrepid coder needs a fast and pythonic way to 'window' the data? This recipe demonstrates how to wrap any iterable with a class that adds two methods, prev and peek.</p>
Yet another Python implementation of PEP 380 (yield from) (Python)
2010-04-25T23:08:07-07:00Arnau Sanchezhttp://code.activestate.com/recipes/users/4173270/http://code.activestate.com/recipes/577153-yet-another-python-implementation-of-pep-380-yield/
<p style="color: grey">
Python
recipe 577153
by <a href="/recipes/users/4173270/">Arnau Sanchez</a>
(<a href="/recipes/tags/coroutine/">coroutine</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/refactor/">refactor</a>).
Revision 3.
</p>
<p>Any Python programmer knows how extremely powerful <a href="http://www.python.org/dev/peps/pep-0255/">generators</a> are. Now (since version 2.5) Python generators can not only yield values but also receive them, so they can be used to build <a href="http://www.python.org/dev/peps/pep-0342/">coroutines</a>.</p>
<p>One drawback of the current implementation of generators is that you can only yield/receive values to/from the immediate caller. That means, basically, that you cannot easily refactor your code and write nested generators. <a href="http://www.python.org/dev/peps/pep-0380/">PEP-380</a> is the most serious effort to overcome this issue, but until it gets approved we can still play around with pure Python implementations of <em>yield from</em>. </p>
<p>This recipe follows terminology used by others in the past (<a href="http://code.activestate.com/recipes/576727">recipe566726</a>, <a href="http://code.activestate.com/recipes/576728">recipe576728</a>), but I've tried to simplify the code as much as possible.</p>
Concurrent buffer for generators (Python)
2010-05-05T22:47:33-07:00Javier Ruerehttp://code.activestate.com/recipes/users/4172765/http://code.activestate.com/recipes/576999-concurrent-buffer-for-generators/
<p style="color: grey">
Python
recipe 576999
by <a href="/recipes/users/4172765/">Javier Ruere</a>
(<a href="/recipes/tags/concurrency/">concurrency</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/iterator/">iterator</a>, <a href="/recipes/tags/threading/">threading</a>).
Revision 2.
</p>
<p>A buffer that will partially consume an iterator in the background.</p>
<p>Very useful for reading files and merging the data using the excellent <a href="http://code.activestate.com/recipes/491285/" rel="nofollow">http://code.activestate.com/recipes/491285/</a></p>
Python Short URL Generator (Python)
2011-09-19T14:06:36-07:00Michael Foglemanhttp://code.activestate.com/recipes/users/4171845/http://code.activestate.com/recipes/576918-python-short-url-generator/
<p style="color: grey">
Python
recipe 576918
by <a href="/recipes/users/4171845/">Michael Fogleman</a>
(<a href="/recipes/tags/deterministic/">deterministic</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/short/">short</a>, <a href="/recipes/tags/tiny/">tiny</a>, <a href="/recipes/tags/unique/">unique</a>, <a href="/recipes/tags/url/">url</a>).
Revision 3.
</p>
<p>Python implementation for generating Tiny URL- and bit.ly-like URLs.</p>
sin, cos, tan for Decimal (Python)
2007-07-05T19:49:49-07:00Alain Mellanhttp://code.activestate.com/recipes/users/4065697/http://code.activestate.com/recipes/523018-sin-cos-tan-for-decimal/
<p style="color: grey">
Python
recipe 523018
by <a href="/recipes/users/4065697/">Alain Mellan</a>
(<a href="/recipes/tags/algorithms/">algorithms</a>, <a href="/recipes/tags/generator/">generator</a>).
Revision 2.
</p>
<p>Implementation of sine, cosine, tangent functions for Decimal arithmetic, using Taylor series expansion. It uses simple numerator and denominator generators.</p>
<p>The nice part is, the code is independent from the Decimal library. Feed it a float, it works just the same as if you feed it a Decimal (apart from the precision :-)</p>
Pluggable Python generators (Python)
2016-03-18T19:11:48-07:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/580628-pluggable-python-generators/
<p style="color: grey">
Python
recipe 580628
by <a href="/recipes/users/4173351/">Vasudev Ram</a>
(<a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/generators/">generators</a>, <a href="/recipes/tags/python/">python</a>).
</p>
<p>This is a simple recipe to show that Python generators are pluggable, i.e., they can be passed as arguments into functions, and then used inside those functions.</p>