1

This may be an OS problem since I did saw on youtube videos where people were demoing how to use decorators in python in a Linux based system.

So I'm trying to play with decorators. In its usual form, you create a function of it first, and then you use the special keywoard "@func_name" in order to pass the next line of arguments into the function. This particular method of utilizing decorator is not working. I've tried in PyDev (Eclipse) and it is just reading as syntax error. I also tried the interactive Python.

Currently running windows OS 7 Python Version 2.78

Here are more specific examples

def c(n):
    def d():
        return "Hello world",n
    return d()


c=c("of Python")
print c
output: ('Hello world', 'of Python')


@c
"of Python"
output:    "of Python?"
               ^
SyntaxError: invalid syntax

Created a working version based on Jon's answer

def c(n):
    def d():
        return "Hello world" + n()
    return d


@c
def decorate_this_func():
    return " python"

print decorate_this_func()
Stanley Chan
  • 45
  • 2
  • 9
  • 3
    You can only decorate a function or class definition. – Ry- Feb 27 '15 at 08:17
  • 1
    Note also that `return d()` should be `return d` and by doing `c=c('of Python')` you're re-binding your decorator... It'll be worth going through the link Tim's provided in his answer as to how to use decorators correctly. – Jon Clements Feb 27 '15 at 08:24
  • Thanks Jon, your answer was quite helpful. – Stanley Chan Mar 02 '15 at 05:33

1 Answers1

1

then you use the special keywoard "@func_name" in order to pass the next line of arguments into the function

That's not how decorators work. You can pass arguments to a decorator like this

@c("of python")
def decorate_this_func():
    pass

But for that to work you need to tweak your decorator function a bit.

Give this a read https://stackoverflow.com/a/1594484/1843331

It's an excellent explanation of decorators, how they work, how to use arguments with decorators and much more.

Community
  • 1
  • 1
Tim
  • 41,901
  • 18
  • 127
  • 145