Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

While I like to think of myself as a reasonably competent Python coder, one aspect of the language I've never been able to grok is decorators.

I know what they are (superficially), I've read tutorials, examples, questions on Stack Overflow, and I understand the syntax, can write my own, occasionally use @classmethod and @staticmethod, but it never occurs to me to use a decorator to solve a problem in my own Python code. I never encounter a problem where I think, "Hmm...this looks like a job for a decorator!".

So, I'm wondering if you guys might offer some examples of where you've used decorators in your own programs, and hopefully, I'll have an "A-ha!" moment and get them.

1 Answer

0 votes
by (106k points)

In Python, we use decorators mainly for timing purposes but we also use it for synchronization below is the code which is using decoder for timing purpose:-

def time_dec(func):

def wrapper(*arg):

t = time.clock()

res = func(*arg)

print func.func_name, time.clock()-t

return res

return wrapper


def myFunction(n):


One can also use decorators for checking parameters type which is passed to their Python methods. No one prefers to repeat the same parameter counting, instead, they will raise an exception. 

Below is the code for the raising exception while using decoder:-

def myMethod(ID, name):

if not (myIsType(ID, 'uint') and myIsType(name, 'utf8string')):

raise BlaBlaException() 

Browse Categories