Annotations in Python

May 15, 2012 under Python

After seeing how do annotations work on Java, we will see how do they work on Python. Because Python is a less strict language, annotations can be use on a more direct way.

For example, if we want to log every time we execute certain functions, we just have to define an interface which prints the log we want and make our functions implement this interface:

from functools import wraps
def log(func):
 @wraps(func)
 def log_func(*args, **kwargs):
  print "log"
  return func(*args, **kwargs)
 return log_func
@log
def func1():
 print "Ejecutando funcion uno"
@log
def func2():
 print "Ejecutando funcion uno"
func1()
func2()

The code above returns this result:

log
Ejecutando función uno
log
Ejecutando función dos

We can also use annotations to more useful things, like telling Python that certain function will be executed on a different thread:

from multiprocessing import process
def run_async(func):
 @wraps(func)
 def async_func(*args, **kwargs):
 func_hl = Process(target = func, args = args, kwargs = kwargs)
 func_hl.start()
 return func_hl
 return async_func
@run_async
 def process():
 print "Ejecutado en asíncrono"

Related Posts:

comments: 0 » tags: ,

High Concurrency in Java

July 30, 2010 under Java

When facing high concurrency applications, we often find a number of generic problems. In this article I will focus on the problems of resources (CPU and memory), allowing synchronization problems for another future article. For now on, I will focus on the most typical and most direct solutions.

When we discover threads and the advantages of parallel processing it can happen that we end up abusing their use. We have a lot of threads (100 ¿? 1000?) simultaneously, and the processor will be jumping from one to another without stopping, not letting them finish, no matter how fast is their real excution. And over time there will be more and more threads only slowing down the process. To the cost of execution of each thread, we must consider also the added cost of creating and destroying threads, which can become significant when we talk about so many threads at once.
Click here to read more.. »

Related Posts: