MObject
MObject

Reputation: 397

Make a pause after each execution of a method

I try to add a pause after each execution of method, there is a way to do it automatically ? Actually i've something like this :

import time
def test (arg):
    print arg
    time.sleep(0.1)
class Foo (Object):
   def __init__ (self, a, b):
       self.a = a
       self.b = b
       time.sleep(0.1)
   def printer (self, arg):
       print arg
       time.sleep(0.1)

Upvotes: 2

Views: 152

Answers (3)

unutbu
unutbu

Reputation: 879691

Here is basically the same thing as @Fedor Gogolev's solution, except that this uses a class decorator instead of a metaclass.

import time
import inspect
import functools

def sleep(f):
    @functools.wraps(f)    
    def wrapper(*args, **kwargs):
        result = f(*args, **kwargs)
        time.sleep(0.1)
        return result
    return wrapper

def sleeper(cls):
    for name, method in inspect.getmembers(cls, inspect.ismethod):
        setattr(cls, name, sleep(method))
    return cls

@sleeper
class Foo(object):
   def __init__(self, a, b):
       self.a = a
       self.b = b
   def printer(self, arg):
       print arg


f = Foo(1,2)
f.printer('hi')

Upvotes: 3

Jon Clements
Jon Clements

Reputation: 142166

You could look at decorators (one could use a class decorator to apply a sleep to each class method for instance), but otherwise, no - not really. One way or another, if you want it to sleep, you should be explicit about it. That way, there'll be less surprises if anyone should want to re-use your code or do timings etc... etc...

Upvotes: 0

Fedor Gogolev
Fedor Gogolev

Reputation: 10541

Yes, your can use metaclasses to modify your class methods in creation, and decorate every function with a special decorator. In your case it could be like this:

#! /usr/bin/env python
#-*- coding:utf-8 -*-

import time

from inspect import isfunction
from functools import wraps

def sleep_decorator(func):
    @wraps(func)
    def inner(*args, **kwargs):
        result = func(*args, **kwargs)
        time.sleep(0.1)
        return result
    return inner

class BaseFoo(type):

    def __new__(cls, name, bases, dct):
        for name in dct:
            if isfunction(dct[name]):
                dct[name] = sleep_decorator(dct[name])
        return type.__new__(cls, name, bases, dct)


class Foo (object):
    __metaclass__ = BaseFoo

    def __init__ (self, a, b):
        self.a = a
        self.b = b

    def printer (self, arg):
        print arg

Upvotes: 2

Related Questions