Question

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
>>>
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top