Reputation: 497
how to use this code in python interactive shell (interpreter):
@makebold
@makeitalic
def hello():
print ("Hello, world!")
in shell I get this error:
>>> @makebold
... hello()
File "<stdin>", line 2
hello()
^
IndentationError: unexpected indent
>>> @makebold
... hello()
File "<stdin>", line 2
hello()
^
SyntaxError: invalid syntax
>>>
Upvotes: 1
Views: 1436
Reputation: 1121834
You are trying to decorate an expression; you forgot to use def
and in one case you even indented the hello()
line. The same code in a Python file will fail with the same errors, there is no difference between the interactive interpreter and a Python source file here.
Decorators only work on classes and functions; if you actually tried to use this with a function definition statement it'd work just fine:
>>> def foo(f):
... return f
...
>>> @foo
... def bar():
... pass
...
If you wanted to apply it to an existing function, you'd need to use:
>>> hello = makebold(hello)
because that is exactly what the @expression
syntax ends up doing.
Upvotes: 4