Feeds:
Posts
Comments

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 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.

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:

  • testsuite1 <-> Feature 1
    • testcase1
    • testcase2
  • testsuite2 <-> Feature 2
    • testcase1
    • testcase2

Continue Reading »

Now, you’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 explore if your code is good or not good. The module must to be used with some kinds of tips & tricks, but I hope this example result helpful.

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:

  • testsuite1 <-> Feature 1
    • testcase1
    • testcase2
  • testsuite2 <-> Feature 2
    • testcase1
    • testcase2

Continue Reading »

Threads (Parte II)

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 típico de concurrencia, y ésta es su versión python:

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 '-> Produced %d' % i

class Consumer (Thread):
	def run (self):
		consumed = 0
		while consumed < elements:
			myLock.acquire ()
			if len (array) > 0:
				e = array[0]
				del array[0]
			myLock.release ()
			print '<- 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 ()

Continue Reading »

Threads (Part II)

If you feel that examples of threads from Threads (Part I) isn’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’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:

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 '-> Produced %d' % i

class Consumer (Thread):
	def run (self):
		consumed = 0
		while consumed < elements:
			myLock.acquire ()
			if len (array) > 0:
				e = array[0]
				del array[0]
			myLock.release ()
			print '<- 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 ()

Continue Reading »

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 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)

Continue Reading »

Hi all, in this post you’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’s look to an example of code:

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)

Continue Reading »

Módulo random

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 <= x < 1.0.
  • uniform (a, b): Genera un número flotante en el rango a<= x < b.
  • randint (a, b): Genera un número entero en el rango a <= x <= b.
  • randrange (a, b, paso): Selecciona un número entero en el rango dado. Este rango es igual al de la función built-in range(a, b, paso).

Y para continuar, funciones sobre secuencias: Continue Reading »

Random module

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 <= x < 1.0.
  • uniform (a, b): Generate a float number in range a<= x < b.
  • randint (a, b): Generate an integer number in range a <= x <= b.
  • randrange (a, b, step): Select an integer number in a given range. This range is equal to built-in range (a, b, step).

And now, functions over sequences:
Continue Reading »

Threads (Parte I)

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.

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.

Vamos a ver un ejemplo simple…

 Continue Reading »

Threads (Part I)

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.

Concerning python, there’s a tip that you have to have in mind. In python, threads are simulated, I mean, when you have 3 threads, really there’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’re not normal threads.

Let’s go to see the example…

 Continue Reading »

Older Posts »