<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Pyzone, a place for Python Language</title>
	<atom:link href="http://pyzone.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://pyzone.wordpress.com</link>
	<description>Notes about interesting Python code snippets</description>
	<lastBuildDate>Thu, 07 Feb 2008 19:34:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='pyzone.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Pyzone, a place for Python Language</title>
		<link>http://pyzone.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://pyzone.wordpress.com/osd.xml" title="Pyzone, a place for Python Language" />
	<atom:link rel='hub' href='http://pyzone.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Testeando tus propios módulos python</title>
		<link>http://pyzone.wordpress.com/2008/02/07/testeando-tus-propios-modulos-python/</link>
		<comments>http://pyzone.wordpress.com/2008/02/07/testeando-tus-propios-modulos-python/#comments</comments>
		<pubDate>Thu, 07 Feb 2008 19:33:20 +0000</pubDate>
		<dc:creator>Rafael Treviño</dc:creator>
				<category><![CDATA[Modulos]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://pyzone.wordpress.com/?p=18</guid>
		<description><![CDATA[Ahora que has mejorado tus habilidades en python, ¿cómo probarlas? Muy simple, hoy quiero mostrarte como probar tus módulos y paquetes que desarrollas en tu tiempo libre o en el trabajo. Testear módulos de python puede hacerse fácilmente con el módulo unittest. Con este módulo (y el tuyo), puedes explorar cuánto de bueno es tu [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=18&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Ahora que has mejorado tus habilidades en python, ¿cómo probarlas? Muy simple, hoy quiero mostrarte como probar tus módulos y paquetes que desarrollas en tu tiempo libre o en el trabajo.</p>
<p>Testear módulos de python puede hacerse fácilmente con el módulo <i>unittest</i>. Con este módulo (y el tuyo), puedes explorar cuánto de bueno es tu código. El módulo debe ser usado con algunos truquitos para obtener todo su potencial, por lo que espero que mi ejemplo sea instructivo.</p>
<p>Para empezar, quiero mostrarte algo de teoría de test. Testear un módulo o un programa se divide en testsuites, una testsuite está compuesta de testcases. Cada testsuite prueba una feature (o característica) del módulo, y cada testcase debe probar una o más funciones o métodos de esa feature. Un ejemplo:</p>
<ul>
<li>testsuite1 &lt;-&gt; Feature 1
<ul>
<li>testcase1</li>
<li>testcase2</li>
</ul>
</li>
<li>testsuite2 &lt;-&gt; Feature 2
<ul>
<li>testcase1</li>
<li>testcase2</li>
</ul>
</li>
</ul>
<p><span id="more-18"></span></p>
<p>Todo eso esta muy bien, pero ¿cómo aplicarlo a un ejemplo? Lo primero de todo, cuando desarrollo un nuevo módulo, creo un nuevo test para ese módulo en un directorio llamado <i>test</i> (no muy original <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . En ese directorio, guardo los tests de una serie de módulos relacionados, y a continuación muestro un ejemplo (no real) de uno de estos tests:</p>
<pre>from sys import path

path.append ('..')from Module import Module, ModuleError

import unittest, logging

class ModuleMethods (unittest.TestCase):

    logging.basicConfig (level = logging.DEBUG,

        format = '%(asctime)s %(levelname)-8s %(message)s')

def setUp (self): # Esto se ejecuta cada vez que se lanza un test
        self.instance = Module (parameters)

def test_method1 (self): # Primer método, comprueba el valor devuelto
        r = self.instance.method1 (params)

        logging.debug ('r = %s' % str (r))

 self.failUnless (r[0] == 0)

def test_method2 (self): # Segundo método, comprueba si lanza una excepción
  	self.failUnlessRaises (ModuleError, self.instance.method2, params)

def tearDown (self): # Ésto se ejecuta después de que cada test haya finalizado
  	pass # Some test tearDown

def run (): # Función de lanzamiento del testcase
    suite = unittest.TestLoader ().loadTestsFromTestCase (ModuleMethods)

    unittest.TextTestRunner (verbosity = 2).run (suite)
 #Punto de entrada de los test
if __name__ == '__main__':

    run ()</pre>
<p>Este ejemplo muestra un ejemplo sencillo de cómo crear un testcase, suficiente para un módulo o una clase con algunos pocos métodos o funciones. El ejemplo crea una nueva clase de testing (heredando de unittest.TestCase) y define algunos métodos test_*, estos métodos serán automáticamente invocados cuando el testRunner sea lanzadao en la función <i>run.</i></p>
<p>En cada método, se prueba un método objetivo, estos métodos son muy simples, pero puedes crear otros mucho más complejos. Una definición de uno de estos métodos es la siguiente:</p>
<ol>
<li>Alguna (o ninguna) configuración del objetivo.</li>
<li>Ejecución del método objetivo.</li>
<li>Manejo de retornos o exceptiones para determinar si el test es PASS (OK) o FAIL (Fallido).</li>
</ol>
<p>Puedes observar funciones como <i>failUnless</i> o failUnlessRaises<i> </i>que hacen comprobaciones condicionales. Si una o más fallan, el test se considera FAIL. Hay dos tipos de FAIL:</p>
<ul>
<li>Error: Un error es un test que no ha fallado alguna verificación, sino que lanza alguna excepción inesperada, bien sea por fallo en el módulo o por fallo en la escritura del testcase.</li>
<li>Failure: Un test que no cumple con las condiciones de todos los chequeos establecidos.</li>
</ul>
<p>Por ahora, toda esta información es suficiente. Para más información acerca del framework de pruebas, visita <a href="http://docs.python.org/lib/module-unittest.html" title="unittest module">este enlace</a>.</p>
<p>Nos vemos! Se aprecia cualquier comentario.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pyzone.wordpress.com/18/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pyzone.wordpress.com/18/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pyzone.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pyzone.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pyzone.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pyzone.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pyzone.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pyzone.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pyzone.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pyzone.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pyzone.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pyzone.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pyzone.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pyzone.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pyzone.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pyzone.wordpress.com/18/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=18&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pyzone.wordpress.com/2008/02/07/testeando-tus-propios-modulos-python/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/081003756212816480f75ba47e28457b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">rafaeltm</media:title>
		</media:content>
	</item>
		<item>
		<title>Testing Python Modules (Part I)</title>
		<link>http://pyzone.wordpress.com/2008/02/06/testing-python-modules-part-i/</link>
		<comments>http://pyzone.wordpress.com/2008/02/06/testing-python-modules-part-i/#comments</comments>
		<pubDate>Wed, 06 Feb 2008 19:57:56 +0000</pubDate>
		<dc:creator>Rafael Treviño</dc:creator>
				<category><![CDATA[Modules]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://pyzone.wordpress.com/?p=17</guid>
		<description><![CDATA[Now, you&#8217;re python skills could be improved, but how can you test it? Very simple, today I want to show you how to test modules and packages that you develop in your spare time or work time. Testing in python can be made by the powerful unittest module. With this module (and yours), you can [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=17&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Now, you&#8217;re python skills could be improved, but how can you test it? Very simple, today I want to show you how to test modules and packages that you develop in your spare time or work time.</p>
<p>Testing in python can be made by the powerful <i>unittest</i> module. With this module (and yours), you can explore if your code is good or not good. The module must to be used with some kinds of tips &amp; tricks, but I hope this example result helpful.</p>
<p>To start I want to show you some testing theory. The testing of a module is divided in testsuites, one testsuite is a set of testcases. Each testsuite tests one feature of your module, and each testcase must test one or more functions or methods of that feature. And example:</p>
<ul>
<li>testsuite1 &lt;-&gt; Feature 1
<ul>
<li>testcase1</li>
<li>testcase2</li>
</ul>
</li>
<li>testsuite2 &lt;-&gt; Feature 2
<ul>
<li>testcase1</li>
<li>testcase2</li>
</ul>
</li>
</ul>
<p><span id="more-17"></span></p>
<p>All of this is ok, but how to apply this to  an example? First of all, when I develop a new module, I create a new test for that module in a <i>test</i> directory inside the module&#8217;s directory. In that directory, I store all the tests for a given set of related modules, and this is one example of one of that tests:</p>
<pre>from sys import path

path.append ('..')from Module import Module, ModuleError

import unittest, logging

class ModuleMethods (unittest.TestCase):

    logging.basicConfig (level = logging.DEBUG,

        format = '%(asctime)s %(levelname)-8s %(message)s')

def setUp (self): # This is executed each time a test is launched

        self.instance = Module (parameters)

def test_method1 (self): # First method, check value returned

        r = self.instance.method1 (params)

        logging.debug ('r = %s' % str (r))

 self.failUnless (r[0] == 0)

def test_method2 (self): # Second method, check exception

  	self.failUnlessRaises (ModuleError, self.instance.method2, params)

def tearDown (self): # This is executed after each test finished

  	pass # Some test tearDown

def run (): # Running function of the test

    suite = unittest.TestLoader ().loadTestsFromTestCase (ModuleMethods)

    unittest.TextTestRunner (verbosity = 2).run (suite)

#Entry point of the test

if __name__ == '__main__':

    run ()</pre>
<p>This example shows you a simple example about creating a testcase, this is enough for a module or class with only a few functions or methods. This example creates a new class of testing (with unittest.TestCase as base class) and define some test_* methods, these methods are automatically invoked when the testRunner will be called in the <i>run</i> function.</p>
<p>In each method, a target method is tested, these methods are pretty simple, but you can make it a lot more complex ones. A definition for one of these methods is the following:</p>
<ol>
<li>Some configuration of the target.</li>
<li>Target execution.</li>
<li>Return value (or exception) handling to determine a FAIL or PASS test.</li>
</ol>
<p>You can see functions like <i>failUnless </i>or <i>failUnlessRaises</i> that makes some conditional checks, if one or more fails, that test is considered FAIL. There are two types of FAIL:</p>
<ul>
<li>Error: An error is a test that raises some unexpected exception, this can be a wrong test or a problem in the target module code.</li>
<li>Failure: A typical error of module code that doesn&#8217;t pass all checks made in the test.</li>
</ul>
<p>For now, I think this information is enough. For further information about this testing framework, check <a href="http://docs.python.org/lib/module-unittest.html" title="unittest module">this link</a>.</p>
<p>See you! Comments welcomed.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pyzone.wordpress.com/17/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pyzone.wordpress.com/17/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pyzone.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pyzone.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pyzone.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pyzone.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pyzone.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pyzone.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pyzone.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pyzone.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pyzone.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pyzone.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pyzone.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pyzone.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pyzone.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pyzone.wordpress.com/17/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=17&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pyzone.wordpress.com/2008/02/06/testing-python-modules-part-i/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/081003756212816480f75ba47e28457b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">rafaeltm</media:title>
		</media:content>
	</item>
		<item>
		<title>Threads (Parte II)</title>
		<link>http://pyzone.wordpress.com/2008/02/05/threads-parte-ii/</link>
		<comments>http://pyzone.wordpress.com/2008/02/05/threads-parte-ii/#comments</comments>
		<pubDate>Tue, 05 Feb 2008 17:26:27 +0000</pubDate>
		<dc:creator>Rafael Treviño</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://pyzone.wordpress.com/?p=16</guid>
		<description><![CDATA[Si sientes que los ejemplos de Threads (Part I) se te quedan pequeños, hoy te traigo un mejor ejemplo (y bien conocido). Se trata del productor-consumidor . Este ejemplo, para quien no lo conozca, está basado en dos actores, uno que produce algo (números en este caso) y otro que los consume. Es una ejemplo [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=16&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Si sientes que los ejemplos de <a href="http://pyzone.wordpress.com/2008/01/25/threads-part-i/" title="Threads (Part I)">Threads (Part I)</a> se te quedan pequeños, hoy te traigo un mejor ejemplo (y bien conocido). Se trata del productor-consumidor <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . Este ejemplo, para quien no lo conozca, está basado en dos actores, uno que produce algo (números en este caso) y otro que los consume. Es una ejemplo típico de concurrencia, y ésta es su versión python:</p>
<pre>from threading import Thread, Lock

array = []
myLock = Lock ()
elements = 10

class Producer (Thread):
	def run (self):
		for i in range (elements):
			myLock.acquire ()
			array.append (i)
			myLock.release ()
			print '-&gt; Produced %d' % i

class Consumer (Thread):
	def run (self):
		consumed = 0
		while consumed &lt; elements:
			myLock.acquire ()
			if len (array) &gt; 0:
				e = array[0]
				del array[0]
			myLock.release ()
			print '&lt;- Consumed %d' % e
			consumed += 1

if __name__ == '__main__':
	p1 = Producer ()
	p2 = Producer ()
	c1 = Consumer ()
	c2 = Consumer ()
	p1.start ()
	c1.start ()
	p2.start ()
	c2.start ()
	p1.join ()
	p2.join ()
	c1.join ()
	c2.join ()</pre>
<p><span id="more-16"></span>Lo primero que se observa es la declaración de variables, incluyendo un Lock (o candado) para el acceder correctamente a la variable compartida <i>array</i>. Después se definen las dos clases principales, una para el productor y la otra para el consumidor. En el final, en el programa principal, se crean dos productores y dos consumidores y se ejecutan hasta el final. Para que los threads acaben correctamente, debes hacer <i>join</i> de todas las instancias. La salida que muestra el script es la siguiente:</p>
<pre>-&gt; Produced 0
-&gt; Produced 1
-&gt; Produced 2
-&gt; Produced 3
-&gt; Produced 4
-&gt; Produced 5
-&gt; Produced 6
-&gt; Produced 7
-&gt; Produced 8
&lt;- Consumed 0
&lt;- Consumed 1
&lt;- Consumed 2
-&gt; Produced 9
&lt;- Consumed 3
&lt;- Consumed 4
&lt;- Consumed 5
&lt;- Consumed 6
&lt;- Consumed 7
-&gt; Produced 0
-&gt; Produced 1
-&gt; Produced 2
&lt;- Consumed 8
&lt;- Consumed 9
-&gt; Produced 3
-&gt; Produced 4
-&gt; Produced 5
-&gt; Produced 6
-&gt; Produced 7
&lt;- Consumed 0
&lt;- Consumed 1
&lt;- Consumed 2
&lt;- Consumed 3
&lt;- Consumed 4
-&gt; Produced 8
-&gt; Produced 9
&lt;- Consumed 5
&lt;- Consumed 6
&lt;- Consumed 7
&lt;- Consumed 8
&lt;- Consumed 9</pre>
<p>Esto es todo por ahora, mantente a la escucha <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . Nos vemos!</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pyzone.wordpress.com/16/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pyzone.wordpress.com/16/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pyzone.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pyzone.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pyzone.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pyzone.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pyzone.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pyzone.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pyzone.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pyzone.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pyzone.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pyzone.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pyzone.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pyzone.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pyzone.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pyzone.wordpress.com/16/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=16&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pyzone.wordpress.com/2008/02/05/threads-parte-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/081003756212816480f75ba47e28457b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">rafaeltm</media:title>
		</media:content>
	</item>
		<item>
		<title>Threads (Part II)</title>
		<link>http://pyzone.wordpress.com/2008/02/04/threads-part-ii/</link>
		<comments>http://pyzone.wordpress.com/2008/02/04/threads-part-ii/#comments</comments>
		<pubDate>Mon, 04 Feb 2008 20:26:19 +0000</pubDate>
		<dc:creator>Rafael Treviño</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Threads]]></category>

		<guid isPermaLink="false">http://pyzone.wordpress.com/?p=15</guid>
		<description><![CDATA[If you feel that examples of threads from Threads (Part I) isn&#8217;t too complex for you, today I bring you a better example (and well known). The producer-consumer example . This example, for the people that don&#8217;t know the case, is based in two actors, one that produces something (numbers in this case) and other [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=15&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If you feel that examples of threads from <a href="http://pyzone.wordpress.com/2008/01/25/threads-part-i/" title="Threads (Part I)">Threads (Part I)</a> isn&#8217;t too complex for you, today I bring you a better example (and well known). The producer-consumer example <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . This example, for the people that don&#8217;t know the case, is based in two actors, one that produces something (numbers in this case) and other that consumes them. This a typical concurrent example, and this is the python version:</p>
<pre>from threading import Thread, Lock

array = []
myLock = Lock ()
elements = 10

class Producer (Thread):
	def run (self):
		for i in range (elements):
			myLock.acquire ()
			array.append (i)
			myLock.release ()
			print '-&gt; Produced %d' % i

class Consumer (Thread):
	def run (self):
		consumed = 0
		while consumed &lt; elements:
			myLock.acquire ()
			if len (array) &gt; 0:
				e = array[0]
				del array[0]
			myLock.release ()
			print '&lt;- Consumed %d' % e
			consumed += 1

if __name__ == '__main__':
	p1 = Producer ()
	p2 = Producer ()
	c1 = Consumer ()
	c2 = Consumer ()
	p1.start ()
	c1.start ()
	p2.start ()
	c2.start ()
	p1.join ()
	p2.join ()
	c1.join ()
	c2.join ()</pre>
<p><span id="more-15"></span>First, you see some variable declaration, including a declaration for a Lock in order to make correct access to the shared variable <i>array</i>. Then two classes are defined, the main classes, one for the producer and another for the consumer. At the end, in the main program, we create two producers and two consumers and they&#8217;re running until the end of their lives. For thread right end, you must <i>join</i> all instances. The output showed by this script is:</p>
<pre>-&gt; Produced 0
-&gt; Produced 1
-&gt; Produced 2
-&gt; Produced 3
-&gt; Produced 4
-&gt; Produced 5
-&gt; Produced 6
-&gt; Produced 7
-&gt; Produced 8
&lt;- Consumed 0
&lt;- Consumed 1
&lt;- Consumed 2
-&gt; Produced 9
&lt;- Consumed 3
&lt;- Consumed 4
&lt;- Consumed 5
&lt;- Consumed 6
&lt;- Consumed 7
-&gt; Produced 0
-&gt; Produced 1
-&gt; Produced 2
&lt;- Consumed 8
&lt;- Consumed 9
-&gt; Produced 3
-&gt; Produced 4
-&gt; Produced 5
-&gt; Produced 6
-&gt; Produced 7
&lt;- Consumed 0
&lt;- Consumed 1
&lt;- Consumed 2
&lt;- Consumed 3
&lt;- Consumed 4
-&gt; Produced 8
-&gt; Produced 9
&lt;- Consumed 5
&lt;- Consumed 6
&lt;- Consumed 7
&lt;- Consumed 8
&lt;- Consumed 9</pre>
<p>This is all for now, stay tuned for more snippets <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . See you!</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pyzone.wordpress.com/15/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pyzone.wordpress.com/15/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pyzone.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pyzone.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pyzone.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pyzone.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pyzone.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pyzone.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pyzone.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pyzone.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pyzone.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pyzone.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pyzone.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pyzone.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pyzone.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pyzone.wordpress.com/15/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=15&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pyzone.wordpress.com/2008/02/04/threads-part-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/081003756212816480f75ba47e28457b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">rafaeltm</media:title>
		</media:content>
	</item>
		<item>
		<title>Threads y decoradores (para thread-safety)</title>
		<link>http://pyzone.wordpress.com/2008/02/02/threads-y-decoradores-para-thread-safety/</link>
		<comments>http://pyzone.wordpress.com/2008/02/02/threads-y-decoradores-para-thread-safety/#comments</comments>
		<pubDate>Sat, 02 Feb 2008 14:35:13 +0000</pubDate>
		<dc:creator>Rafael Treviño</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Threads]]></category>

		<guid isPermaLink="false">http://pyzone.wordpress.com/?p=14</guid>
		<description><![CDATA[Hoy aprenderás cómo los decoradores pueden hacer tu vida más fácil cuando manejas threads. Cualquiera que haya usado threads ha tenido que pelearse con sus problemas. Uno de los más importantes son las condiciones de carrera (race-conditions). Pero con los decoradores, esto puede ser fácilmente eliminado. Vamos a ver un ejemplo de código. from threading [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=14&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hoy aprenderás cómo los decoradores pueden hacer tu vida más fácil cuando manejas threads. Cualquiera que haya usado threads ha tenido que pelearse con sus problemas. Uno de los más importantes son las condiciones de carrera (race-conditions). Pero con los decoradores, esto puede ser fácilmente eliminado. Vamos a ver un ejemplo de código.</p>
<pre>from threading import Thread import time
import random

criticalVar = 0
threads = 10

class MyThread (Thread):

	def __init__ (self, id):
		Thread.__init__ (self)
		self.TID = id # Thread id

	def run (self):
		global criticalVar
		print 'Thread [%d] starts' % self.TID
		localVar = criticalVar + 1
		time.sleep (random.random ()) # Some long call between 0 and 1
		criticalVar = localVar
		print 'Thread [%d] ends: criticalVar = %d' % (self.TID, criticalVar)

if __name__ == '__main__':
	s = time.time ()
	threadBag = []
	for id in range (threads):
		t = MyThread (id)
		t.start ()
		threadBag.append (t)
	for thread in threadBag:
		thread.join ()
	print 'Total time = %f' % (time.time () - s)</pre>
<p><span id="more-14"></span><br />
Este código muestra un ejemplo típico de threads. Si lanzas este ejemplo, mostrará:</p>
<pre>Thread [0] starts
Thread [1] starts
Thread [2] starts
Thread [3] starts
Thread [4] starts
Thread [5] starts
Thread [6] starts
Thread [7] starts
Thread [8] starts
Thread [9] starts
Thread [0] ends: criticalVar = 1
Thread [2] ends: criticalVar = 1
Thread [3] ends: criticalVar = 1
Thread [9] ends: criticalVar = 1
Thread [4] ends: criticalVar = 1
Thread [5] ends: criticalVar = 1
Thread [7] ends: criticalVar = 1
Thread [8] ends: criticalVar = 1
Thread [1] ends: criticalVar = 1
Thread [6] ends: criticalVar = 1
Total time = 0.872000</pre>
<p>La salida muestra una preciosa condición de carrera en <i>criticalVar</i> ya que todos los threads leen la variable, hacen algo que consume tiempo y la escriben después de que todos la hayan leido. Este comportamiento lleva a un fallo porque la función <i>run()</i> no es segura para threads (thread-safety).</p>
<p>Pero, con un pequeño decorador y alguna magía de locks&#8230;</p>
<pre>from threading import Thread, Lock
import time
import random

criticalVar = 0
threads = 10
myLock = Lock ()

def sync (lock):
	def function (f):
		def wrapper (*args, **kargs):
			lock.acquire ()
			try:
				return f(*args, **kargs)
			finally: # exec in all cases
				lock.release ()
		return wrapper
	return function

class MyThread (Thread):

	def __init__ (self, id):
		Thread.__init__ (self)
		self.TID = id # Thread id

	@sync (myLock)
	def run (self):
		global criticalVar
		print 'Thread [%d] starts' % self.TID
		localVar = criticalVar + 1
		time.sleep (random.random ()) # Some long call between 0 and 1
		criticalVar = localVar
		print 'Thread [%d] ends: criticalVar = %d' % (self.TID, criticalVar)

if __name__ == '__main__':
	s = time.time ()
	threadBag = []
	for id in range (threads):
		t = MyThread (id)
		t.start ()
		threadBag.append (t)
	for thread in threadBag:
		thread.join ()
	print 'Total time = %f' % (time.time () - s)</pre>
<p>Ésta es la versión segura. Con el decorador al principio de la función <i>run(),</i> cada thread tiene que adquirir el lock y liberarlo al terminar. Por lo que el decorador hace la función <i>run()</i> segura ant threads y la salida queda:</p>
<pre>Thread [0] starts
Thread [0] ends: criticalVar = 1
Thread [1] starts
Thread [1] ends: criticalVar = 2
Thread [2] starts
Thread [2] ends: criticalVar = 3
Thread [3] starts
Thread [3] ends: criticalVar = 4
Thread [4] starts
Thread [4] ends: criticalVar = 5
Thread [5] starts
Thread [5] ends: criticalVar = 6
Thread [6] starts
Thread [6] ends: criticalVar = 7
Thread [7] starts
Thread [7] ends: criticalVar = 8
Thread [8] starts
Thread [8] ends: criticalVar = 9
Thread [9] starts
Thread [9] ends: criticalVar = 10
Total time = 3.315000</pre>
<p>Esta salida sólo tiene un problema: <i>Total time.</i> Con la adición del decorador, el script se comporta de forma secuencial en vez de paralela, pero eso es una efecto conocido de la seguridad de threads. En cualquier caso, el script corre correctamente, y eso es lo más importante.</p>
<p>Para más información sobre <a href="http://pyzone.wordpress.com/2008/01/26/threads-parte-i/" title="Threads (Parte I)" target="_blank">Threads</a> y <a href="http://pyzone.wordpress.com/2008/01/22/decoradores/" title="Decoradores">Decoradores</a>.</p>
<p>Esto es todo por ahora <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . Los comentarios son bienvenidos.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pyzone.wordpress.com/14/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pyzone.wordpress.com/14/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pyzone.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pyzone.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pyzone.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pyzone.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pyzone.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pyzone.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pyzone.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pyzone.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pyzone.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pyzone.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pyzone.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pyzone.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pyzone.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pyzone.wordpress.com/14/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=14&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pyzone.wordpress.com/2008/02/02/threads-y-decoradores-para-thread-safety/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/081003756212816480f75ba47e28457b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">rafaeltm</media:title>
		</media:content>
	</item>
		<item>
		<title>Threads and decorators (for thread-safety)</title>
		<link>http://pyzone.wordpress.com/2008/02/01/threads-and-decorators-for-thread-safety/</link>
		<comments>http://pyzone.wordpress.com/2008/02/01/threads-and-decorators-for-thread-safety/#comments</comments>
		<pubDate>Fri, 01 Feb 2008 14:23:18 +0000</pubDate>
		<dc:creator>Rafael Treviño</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Threads]]></category>

		<guid isPermaLink="false">http://pyzone.wordpress.com/?p=13</guid>
		<description><![CDATA[Hi all, in this post you&#8217;ll learn how decorators can make your life easier when dealing with threads. Anyone that has experience with threads also have experience with its troubles. One of the most important troubles with threads are race-conditions. But with decorators, this can be easily throw away. Let&#8217;s look to an example of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=13&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hi all, in this post you&#8217;ll learn how decorators can make your life easier when dealing with threads. Anyone that has experience with threads also have experience with its troubles. One of the most important troubles with threads are race-conditions. But with decorators, this can be easily throw away. Let&#8217;s look to an example of code:</p>
<pre>from threading import Thread import time
import random

criticalVar = 0
threads = 10

class MyThread (Thread):

	def __init__ (self, id):
		Thread.__init__ (self)
		self.TID = id # Thread id

	def run (self):
		global criticalVar
		print 'Thread [%d] starts' % self.TID
		localVar = criticalVar + 1
		time.sleep (random.random ()) # Some long call between 0 and 1
		criticalVar = localVar
		print 'Thread [%d] ends: criticalVar = %d' % (self.TID, criticalVar)

if __name__ == '__main__':
	s = time.time ()
	threadBag = []
	for id in range (threads):
		t = MyThread (id)
		t.start ()
		threadBag.append (t)
	for thread in threadBag:
		thread.join ()
	print 'Total time = %f' % (time.time () - s)</pre>
<p><span id="more-13"></span>This code shows a typical threading example. If you run this example it will show:</p>
<pre>Thread [0] starts
Thread [1] starts
Thread [2] starts
Thread [3] starts
Thread [4] starts
Thread [5] starts
Thread [6] starts
Thread [7] starts
Thread [8] starts
Thread [9] starts
Thread [0] ends: criticalVar = 1
Thread [2] ends: criticalVar = 1
Thread [3] ends: criticalVar = 1
Thread [9] ends: criticalVar = 1
Thread [4] ends: criticalVar = 1
Thread [5] ends: criticalVar = 1
Thread [7] ends: criticalVar = 1
Thread [8] ends: criticalVar = 1
Thread [1] ends: criticalVar = 1
Thread [6] ends: criticalVar = 1
Total time = 0.872000</pre>
<p>The output prints a pretty race-condition in the <i>criticalVar</i> because all threas reads the variable, make something time-consuming and then writes the variable. This behaviour leads to a failure because of the not thread-safety function <i>run()</i>.</p>
<p>But, with a little decorator and some lock magic&#8230;</p>
<pre>from threading import Thread, Lock
import time
import random

criticalVar = 0
threads = 10
myLock = Lock ()

def sync (lock):
	def function (f):
		def wrapper (*args, **kargs):
			lock.acquire ()
			try:
				return f(*args, **kargs)
			finally: # exec in all cases
				lock.release ()
		return wrapper
	return function

class MyThread (Thread):

	def __init__ (self, id):
		Thread.__init__ (self)
		self.TID = id # Thread id

	@sync (myLock)
	def run (self):
		global criticalVar
		print 'Thread [%d] starts' % self.TID
		localVar = criticalVar + 1
		time.sleep (random.random ()) # Some long call between 0 and 1
		criticalVar = localVar
		print 'Thread [%d] ends: criticalVar = %d' % (self.TID, criticalVar)

if __name__ == '__main__':
	s = time.time ()
	threadBag = []
	for id in range (threads):
		t = MyThread (id)
		t.start ()
		threadBag.append (t)
	for thread in threadBag:
		thread.join ()
	print 'Total time = %f' % (time.time () - s)</pre>
<p>This is a thread-safe version. With the decorator at the begin of the <i>run()</i> function, each thread has to acquire the lock and release it when it finish. So, this decorator makes <i>run()</i> thread safe and the output is:</p>
<pre>Thread [0] starts
Thread [0] ends: criticalVar = 1
Thread [1] starts
Thread [1] ends: criticalVar = 2
Thread [2] starts
Thread [2] ends: criticalVar = 3
Thread [3] starts
Thread [3] ends: criticalVar = 4
Thread [4] starts
Thread [4] ends: criticalVar = 5
Thread [5] starts
Thread [5] ends: criticalVar = 6
Thread [6] starts
Thread [6] ends: criticalVar = 7
Thread [7] starts
Thread [7] ends: criticalVar = 8
Thread [8] starts
Thread [8] ends: criticalVar = 9
Thread [9] starts
Thread [9] ends: criticalVar = 10
Total time = 3.315000</pre>
<p>This output only has one problem: <i>Total time</i>. Since thread-safe decorator, script behaves sequential instead of  parallel, but it&#8217;s a known effect of thread-safety. Any case, script runs correctly, and this is the most important thing.</p>
<p>For further information about <a href="http://pyzone.wordpress.com/2008/01/25/threads-part-i/" title="Threads (Part I)">Threads</a> and <a href="http://pyzone.wordpress.com/2008/01/21/decorators/" title="Decorators">Decorators</a>.</p>
<p>This is all for now <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . Comments welcomed.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pyzone.wordpress.com/13/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pyzone.wordpress.com/13/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pyzone.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pyzone.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pyzone.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pyzone.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pyzone.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pyzone.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pyzone.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pyzone.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pyzone.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pyzone.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pyzone.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pyzone.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pyzone.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pyzone.wordpress.com/13/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=13&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pyzone.wordpress.com/2008/02/01/threads-and-decorators-for-thread-safety/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/081003756212816480f75ba47e28457b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">rafaeltm</media:title>
		</media:content>
	</item>
		<item>
		<title>Módulo random</title>
		<link>http://pyzone.wordpress.com/2008/01/28/modulo-random/</link>
		<comments>http://pyzone.wordpress.com/2008/01/28/modulo-random/#comments</comments>
		<pubDate>Mon, 28 Jan 2008 20:17:10 +0000</pubDate>
		<dc:creator>Rafael Treviño</dc:creator>
				<category><![CDATA[Modulos]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://pyzone.wordpress.com/?p=12</guid>
		<description><![CDATA[Hola amigos, las funciones aleatorias son muy útiles en más casos de los que piensas. Hoy voy a darte algunas notas sobre aleatorizar tus scripts python con el módulo random. Este simple módulo tiene algunas interesantes funciones para ver más de cerca: random (): Genera un número flotante en el rango 0.0 &#60;= x &#60; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=12&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hola amigos, las funciones aleatorias son muy útiles en más casos de los que piensas. Hoy voy a darte algunas notas sobre aleatorizar tus scripts python con el módulo <i>random.</i> Este simple módulo tiene algunas interesantes funciones para ver más de cerca:</p>
<ul>
<li><i>random ()</i>: Genera un número flotante en el rango 0.0 &lt;= x &lt; 1.0.</li>
<li><i>uniform (a, b)</i>: Genera un número flotante en el rango a&lt;= x &lt; b.</li>
<li><i>randint (a, b)</i>: Genera un número entero en el rango a &lt;= x &lt;= b.</li>
</ul>
<ul>
<li><i>randrange (a, b, paso)</i>: Selecciona un número entero en el rango dado. Este rango es igual al de la función built-in <i>range(a, b, paso).</i></li>
</ul>
<p>Y para continuar, funciones sobre secuencias: <span id="more-12"></span></p>
<ul>
<li><i>choice (secuencia)</i>: Devuelve un elemento de la secuencia.</li>
<li><i>shuffle (</i><i>secuencia</i><i>)</i>: Altera el orden de los elementos en la misma secuencia (la misma referencia).</li>
<li><i>sample (</i><i>secuencia</i><i>, n)</i>: Devuelve una nueva secuencia de longitud <i>n</i> con elemento de la secuencia.</li>
<li><i>populate (</i><i>secuencia</i><i>, n)</i>: Lo mismo que <i>sample</i>, pero los elementos de la nueva secuencia no tienen repeticiones.</li>
</ul>
<p>Para más información sobre el módulo <i>random</i>, visita <a href="http://docs.python.org/lib/module-random.html" title="Random module" target="_blank">este enlace</a>.</p>
<p>Esto es todo por ahora. Mantente atento para más código interesante. Los comentarios siempre son bienvenidos.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pyzone.wordpress.com/12/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pyzone.wordpress.com/12/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pyzone.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pyzone.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pyzone.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pyzone.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pyzone.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pyzone.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pyzone.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pyzone.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pyzone.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pyzone.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pyzone.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pyzone.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pyzone.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pyzone.wordpress.com/12/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=12&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pyzone.wordpress.com/2008/01/28/modulo-random/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/081003756212816480f75ba47e28457b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">rafaeltm</media:title>
		</media:content>
	</item>
		<item>
		<title>Random module</title>
		<link>http://pyzone.wordpress.com/2008/01/27/random-module/</link>
		<comments>http://pyzone.wordpress.com/2008/01/27/random-module/#comments</comments>
		<pubDate>Sun, 27 Jan 2008 13:38:12 +0000</pubDate>
		<dc:creator>Rafael Treviño</dc:creator>
				<category><![CDATA[Modules]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://pyzone.wordpress.com/?p=11</guid>
		<description><![CDATA[Hi folks, random functions are very useful in more cases that you think. Today I will give you some tips about randomizing python scripts with the random module. This simple module has some interesting functions to see deeper: random (): Generate a float number in range 0.0 &#60;= x &#60; 1.0. uniform (a, b): Generate [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=11&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hi folks, random functions are very useful in more cases that you think. Today I will give you some tips about randomizing python scripts with the <i>random </i>module. This simple module has some interesting functions to see deeper:</p>
<ul>
<li><i>random ()</i>: Generate a float number in range 0.0 &lt;= x &lt; 1.0.</li>
<li><i>uniform (a, b)</i>: Generate a float number in range a&lt;= x &lt; b.</li>
<li><i>randint (a, b)</i>: Generate an integer number in range a &lt;= x &lt;= b.</li>
</ul>
<ul>
<li><i>randrange (a, b, step)</i>: Select an integer number in a given range. This range is equal to built-in <i>range (a, b, step).</i></li>
</ul>
<p>And now, functions over sequences:<br />
<span id="more-11"></span></p>
<ul>
<li><i>choice (sequence)</i>: Return an element of the sequence.</li>
<li><i>shuffle (sequence)</i>: Shuffle element of sequence in-place (the same sequence reference).</li>
<li><i>sample (sequence, n)</i>: Return a new sequence of <i>n</i> length with elements from sequence.</li>
<li><i>populate (sequence, n)</i>: The same as <i>sample</i>, but elements of new sequence don&#8217;t have repetitions.</li>
</ul>
<p>For more information about random module, <a href="http://docs.python.org/lib/module-random.html" title="Random module" target="_blank">visit this</a>.</p>
<p>This is all for now. Stay tuned for more interesting code snippets. Comments welcomed.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pyzone.wordpress.com/11/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pyzone.wordpress.com/11/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pyzone.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pyzone.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pyzone.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pyzone.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pyzone.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pyzone.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pyzone.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pyzone.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pyzone.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pyzone.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pyzone.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pyzone.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pyzone.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pyzone.wordpress.com/11/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=11&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pyzone.wordpress.com/2008/01/27/random-module/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/081003756212816480f75ba47e28457b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">rafaeltm</media:title>
		</media:content>
	</item>
		<item>
		<title>Threads (Parte I)</title>
		<link>http://pyzone.wordpress.com/2008/01/26/threads-parte-i/</link>
		<comments>http://pyzone.wordpress.com/2008/01/26/threads-parte-i/#comments</comments>
		<pubDate>Sat, 26 Jan 2008 15:38:36 +0000</pubDate>
		<dc:creator>Rafael Treviño</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Threads]]></category>

		<guid isPermaLink="false">http://pyzone.wordpress.com/?p=10</guid>
		<description><![CDATA[Todo el mundo ha oído hablar de los threads, pero ¿Cómo conseguir threads en python? Hoy espero poder explicártelo. Antes de nada, los threads (o hilos) son básicamente flujos de ejecución. Cada uno de estos flujos de ejecución corre independientemente de los demás, así que si quieres realizar entrada/salida de disco (o cualquier otra operación [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=10&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Todo el mundo ha oído hablar de los threads, pero ¿Cómo conseguir threads en python? Hoy espero poder explicártelo. Antes de nada, los threads (o hilos) son básicamente flujos de ejecución. Cada uno de estos flujos de ejecución corre independientemente de los demás, así que si quieres realizar entrada/salida de disco (o cualquier otra operación que consuma tiempo) y a la vez algo de cómputo, los threads son lo que buscas.</p>
<p>En lo tocante a python, hay una pequeña nota acerca de los threads a tener en cuenta. Los threads en python son simulados, es decir, si tienes 3 threads, realmente sólo existe uno, pero ése (el intérprete python) intercambia la ejecución de tus 3 threads de una manera planificada para simular el comportamiento de los threads. Por lo tanto, los threads de python se comportan como threads normales pero no son threads normales.</p>
<p>Vamos a ver un ejemplo simple&#8230;</p>
<pre><span id="more-10"></span>from threading import Thread import time
import random

threads = 10

class MyThread (Thread):

	def __init__ (self, id):
		Thread.__init__ (self)
		self.TID = id # Thread id

	def run (self):
		print 'Thread [%d] starts' % self.TID
		time.sleep (random.random ()) # Some long call between 0 and 1
		print 'Thread [%d] ends' % self.TID
		self.status = random.randrange (10)

if __name__ == '__main__':
	s = time.time ()
	threadBag = []
	for id in range (threads):
		t = MyThread (id)
		t.start ()
		threadBag.append (t)
	for thread in threadBag:
		thread.join ()
		print 'Thread [%d] returned %d' % (thread.TID, thread.status)
	print 'Total time = %f' % (time.time () - s)</pre>
<p>Este es un primer ejemplo sencillo utilizando threads en python. Cada thread es una instancia de una clase derivada de <i>threading.Thread</i>. Puedes ver que <i>MyThread</i> es esa clase. El método de ejecución es <i>run (self)</i> que es invocado desde la clase base. Debes poner todo el código del thread dentro de este método para ejecutarlo. El thread terminará al retorno de ese método. El otro método utilizado es <i>__init__</i>. Si necesitas pasar datos al thread, éste es tu métdo. Almacena todos los datos en variables de instancia (atributos) y disfruta! Para devolver un valor desde el thread, utiliza <i>self.status</i> y recupéralo cuando hagas el <i>join ()</i> del thread.</p>
<p>El ejemplo sencillo crea algunos threads, los lanza (con el método <i>start()</i>) y después los reúne para recuperar su estado de salida. También calcula el tiempo necesario para todo el script. La salida (variable, debido al uso del módulo <i>random</i>) es:</p>
<pre>Thread [0] starts
Thread [1] starts
Thread [2] starts
Thread [3] starts
Thread [4] starts
Thread [5] starts
Thread [6] starts
Thread [7] starts
Thread [8] starts
Thread [9] starts
Thread [0] ends
Thread [0] returned 2
Thread [3] ends
Thread [5] ends
Thread [1] ends
Thread [1] returned 7
Thread [6] ends
Thread [9] ends
Thread [4] ends
Thread [7] ends
Thread [2] ends
Thread [2] returned 2
Thread [3] returned 2
Thread [4] returned 5
Thread [5] returned 3
Thread [6] returned 2
Thread [7] returned 5
Thread [8] ends
Thread [8] returned 2
Thread [9] returned 6
Total time = 0.861000</pre>
<p>Fíjate en los &#8216;ends&#8217; de los threads, ya que la creación y reunión de los threads son bucles secuenciales, por lo que siempre saldrán en orden. Puedes ver que los threads necesitan diferentes tiempos para terminar. Pero la magía consiste en que el tiempo total de todo el script es, más o menos, el máximo de los tiempos aleatorios, así que ¡La ejecución es paralela!!!</p>
<p>Para más información sobre threads, visita <a href="http://docs.python.org/lib/module-threading.html" title="Módulo threading" target="_blank">este link</a>.</p>
<p>Por ahora es todo. Cualquier comentario es bienvenido.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pyzone.wordpress.com/10/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pyzone.wordpress.com/10/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pyzone.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pyzone.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pyzone.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pyzone.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pyzone.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pyzone.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pyzone.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pyzone.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pyzone.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pyzone.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pyzone.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pyzone.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pyzone.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pyzone.wordpress.com/10/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=10&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pyzone.wordpress.com/2008/01/26/threads-parte-i/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/081003756212816480f75ba47e28457b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">rafaeltm</media:title>
		</media:content>
	</item>
		<item>
		<title>Threads (Part I)</title>
		<link>http://pyzone.wordpress.com/2008/01/25/threads-part-i/</link>
		<comments>http://pyzone.wordpress.com/2008/01/25/threads-part-i/#comments</comments>
		<pubDate>Fri, 25 Jan 2008 13:43:46 +0000</pubDate>
		<dc:creator>Rafael Treviño</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Threads]]></category>

		<guid isPermaLink="false">http://pyzone.wordpress.com/?p=9</guid>
		<description><![CDATA[Everyone has heard about threads, but how to get into python threads? Today I hope I can explain you. First of all, threads are basically execution flows. Each of this execution flows runs independently from another, so if you want to make a lot of disk IO (or any time-consuming task) and at the same [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=9&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Everyone has heard about threads, but how to get into python threads? Today I hope I can explain you. First of all, threads are basically execution flows. Each of this execution flows runs independently from another, so if you want to make a lot of disk IO (or any time-consuming task) and at the same time some computing, threads are for you.</p>
<p>Concerning python, there&#8217;s a tip that you have to have in mind. In python, threads are simulated, I mean, when you have 3 threads, really there&#8217;s only one, but that one (the python interpreter) swaps between your 3 threads in a scheduled manner to simulate threads behaviour. So, python threads behaves as normal threads but they&#8217;re not normal threads.</p>
<p>Let&#8217;s go to see the example&#8230;</p>
<pre><span id="more-9"></span>from threading import Thread import time
import random

threads = 10

class MyThread (Thread):

	def __init__ (self, id):
		Thread.__init__ (self)
		self.TID = id # Thread id

	def run (self):
		print 'Thread [%d] starts' % self.TID
		time.sleep (random.random ()) # Some long call between 0 and 1
		print 'Thread [%d] ends' % self.TID
		self.status = random.randrange (10)

if __name__ == '__main__':
	s = time.time ()
	threadBag = []
	for id in range (threads):
		t = MyThread (id)
		t.start ()
		threadBag.append (t)
	for thread in threadBag:
		thread.join ()
		print 'Thread [%d] returned %d' % (thread.TID, thread.status)
	print 'Total time = %f' % (time.time () - s)</pre>
<p>This a simple first example of using threads in python. Every thread in python is an instance of a derived class of <i>threading.Thread. </i>You can see that class <i>MyThread</i> is that class. The method of execution is <i>run (self) </i>that is invoked by the base class. You have to put all your thread&#8217;s code into that method in order to execute it. Thread will end when this method return. The other method to override is <i>__init__</i>. If you want to pass some data to the thread, this is your method. Save all the data in instance&#8217;s variables and enjoy! To return a value from thread, use <i>self.status</i> and recover it in <i>join ()</i> call.</p>
<p>The example simply creates some threads, launch them (with <i>start()</i> method) and then join them to recover their exit status. Also calculates the time needed for all the script. The (variable, because I use <i>random</i> module) output is:</p>
<pre>Thread [0] starts
Thread [1] starts
Thread [2] starts
Thread [3] starts
Thread [4] starts
Thread [5] starts
Thread [6] starts
Thread [7] starts
Thread [8] starts
Thread [9] starts
Thread [0] ends
Thread [0] returned 2
Thread [3] ends
Thread [5] ends
Thread [1] ends
Thread [1] returned 7
Thread [6] ends
Thread [9] ends
Thread [4] ends
Thread [7] ends
Thread [2] ends
Thread [2] returned 2
Thread [3] returned 2
Thread [4] returned 5
Thread [5] returned 3
Thread [6] returned 2
Thread [7] returned 5
Thread [8] ends
Thread [8] returned 2
Thread [9] returned 6
Total time = 0.861000</pre>
<p>You only have to focus on &#8216;ends&#8217; of threads, because creation and joining are sequential  loops. You can see each thread needs a different time to end. But the magic here is that the total amount of time of the whole script is, more or less, the maximum of the random time values, so execution is parallel!!!</p>
<p>For more information about threads, <a href="http://docs.python.org/lib/module-threading.html" title="Threading module" target="_blank">visit this</a>.</p>
<p>This is all for now. Comments welcomed!</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/pyzone.wordpress.com/9/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/pyzone.wordpress.com/9/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/pyzone.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/pyzone.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/pyzone.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/pyzone.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/pyzone.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/pyzone.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/pyzone.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/pyzone.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/pyzone.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/pyzone.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/pyzone.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/pyzone.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/pyzone.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/pyzone.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=pyzone.wordpress.com&amp;blog=2560723&amp;post=9&amp;subd=pyzone&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://pyzone.wordpress.com/2008/01/25/threads-part-i/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/081003756212816480f75ba47e28457b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">rafaeltm</media:title>
		</media:content>
	</item>
	</channel>
</rss>
