user2399453
user2399453

Reputation: 3081

Importing and using a decorator in another file

I have a simple decorator like this below. However when I import the python file it immediately runs and I can't call the function again. How are decorators supposed to be used?

def plain_decorator(func):
    def decorated_func():
        print "Decorating"
        func()
        print "Decorated"
    return decorated_func()

@plain_decorator
def hw():
    print "Hello Decorators!"

>>> import decorator_ex2 as d
Decorating
Hello Decorators!
Decorated
>>> d.hw()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>> 

Upvotes: 0

Views: 4294

Answers (1)

pushpendra chauhan
pushpendra chauhan

Reputation: 2375

try using this, its because you are calling your inner(decorated_func) function when you return from outer(plain_decorator) function

def plain_decorator(func):
    def decorated_func():
        print "Decorating"
        func()
        print "Decorated"
    return decorated_func

@plain_decorator
def hw():
    print "Hello Decorators!"

Upvotes: 2

Related Questions