Fun with eval()


In [10]:
def update(a, b, c):
    print a, b, c
    return "le retour"
    
test = compile("update('allo', 'comment', 'va')", '<string>', 'eval')

eval(test)
#exec test


allo comment va
Out[10]:
'le retour'

Fun with class decorator


In [135]:
import functools

class MyClassDecorator(object):
    """ I cannot make this decorator to work!"""
    
    def __init__(self, cls):
        self.cls = cls
        super(MyClassDecorator, self).__init__()
    
    def __call__(self, *args, **kwds):
        return self.cls(*args, **kwds)

class MyClassDecoratorWithEmptyArgs(object):
    """ This work if called with an empty argument list:
    ex: 
        @MyBetterClassDecorator()
    """
    
    def __init__(self):
        super(MyClassDecoratorWithEmptyArgs, self).__init__()
        
    def __call__(self, cls):
        return cls
    
 
def my_better_class_decorator(cls):
    def you_got_decorated(*args, **kwds):
        print "I don't who I am anymore!"
    setattr(cls, "static_method", you_got_decorated)
    return cls

def my_better_class_decorator_with_args(value):
    def class_rebuilder(cls):
        def you_got_decorated(*args, **kwds):
            print "I think I am %s!" % value
        setattr(cls, "static_method", you_got_decorated)
        return cls
    return class_rebuilder



class A(object):
    
    def __init__(self):
        super(A, self).__init__()

#@MyClassDecorator
#@MyClassDecoratorWithEmptyArgs()
@my_better_class_decorator
#@my_better_class_decorator_with_args("marvelous")
class MyClass(A):
    
    def __init__(self, value):
        self.value = value  # pass a value juste to test it works
        super(MyClass, self).__init__()
        
    def instance_method(self):
        print "instance method called!"
        
    @classmethod
    def class_method(cls):
        print "class method called!"
    
    @staticmethod
    def static_method():
        print "static method called!"
        
test = MyClass(1)

test.instance_method()
test.class_method()
test.static_method()


instance method called!
class method called!
I don't who I am anymore!

Decorating all class methods with a class decorator


In [28]:
from inspect import isfunction, ismethod, isclass
import time

profiling_enabled = True

def is_profile_enabled():
    return profiling_enabled

def profile(cls):

    print profiling_enabled
    def profile_function(func):
        def wrapped(*args, **kwds):
            if not profiling_enabled:
                print "No profiling for " + func.__name__
                return func(*args, **kwds)
            start = time.time()
            result = func(*args, **kwds)
            print "Execution time for %s: %.2f" % (func.__name__, time.time() - start)
            return result
        return wrapped

    if isclass(cls):
        for k, v in cls.__dict__.iteritems():
            if isinstance(v, classmethod):
               setattr(cls, k, classmethod(profile_function(v.__func__)))
            elif isinstance(v, staticmethod):
                setattr(cls, k, staticmethod(profile_function(v.__func__)))
            elif isfunction(v):
                setattr(cls, k, profile_function(v))
        return cls
    return profile_function(cls)

    
    
    

@profile
class MyClass(object):
    
    def __init__(self, value):
        self.value = value  # pass a value juste to test it works
        super(MyClass, self).__init__()
        
    def instance_method(self):
        time.sleep(0.1)
        #print "instance method called!"
        
    @classmethod
    def class_method(cls):
        time.sleep(0.2)
        #print "class method called!"
    
    @staticmethod
    def static_method():
        time.sleep(0.1)
        #print "static method called!"

@profile
def profiled_function(x, y, z):
    pass
    #print "I am profiled too! %s %s %s" % (x, y, z)
    
test = MyClass(1)
print test.value

test.instance_method()
test.class_method()
test.static_method()

profiled_function("a", "b", "c")

profiling_enabled = False

test.instance_method()
test.class_method()
test.static_method()

profiled_function("a", "b", "c")


True
True
Execution time for __init__: 0.00
1
Execution time for instance_method: 0.10
Execution time for class_method: 0.20
Execution time for static_method: 0.10
Execution time for profiled_function: 0.00
No profiling for instance_method
No profiling for class_method
No profiling for static_method
No profiling for profiled_function

Compare performance of for loop and list comprehension


In [7]:
def list_comprehension():
    return [number for number in xrange(1000)]

def for_loop():
    x = []
    for number in xrange(1000):
        x.append(number)
    return x

%timeit -n 1000 list_comprehension()
%timeit -n 1000 for_loop()


1000 loops, best of 3: 43.9 µs per loop
1000 loops, best of 3: 121 µs per loop

It seems that with this simple example, list comprehension is twice as fast as for loop!

Use regex to extract patterns


In [15]:
import re

p = re.compile(r'(?P<aggregation>.*)\((?P<parameters>.*)\)')
m = p.match('x(y,z)')

print "Pattern found in strings:"
print m.groups()

print ""
print "Using named groups: "
print m.group('aggregation')
print m.group('parameters')

print ""
print "Split parameters:"
print m.group('parameters').split(',')

print ""
print "Behaviour when fetching unexisting named group:"
try:
    print m.group('unknown')
except IndexError:
    print "*Group is not found has expected"


Pattern found in strings:
('x', 'y,z')

Using named groups: 
x
y,z

Split parameters:
['y', 'z']

Behaviour when fetching unexisting named group:
Group is not found has expected

In [ ]: