It seems to me that the error is related in _input
but im not sure
import random
from functools import wraps
_input = input()
def name(command='help'):
def _name(func):
@wraps(func)
def inner(*args, **kwargs):
if _input == command:
func(*args, **kwargs)
return inner
return _name
@name(command='test')
def poo():
print('5')
@name(command='test_2')
def foo():
print('Hello')
>>>test
5
(Sorry for my English)
CodePudding user response:
I think there is just a misunderstanding here. You seem to think that if you run the code and type test
it should run poo
. (ugh, what a name). But it won't run anything at all, because the only executed lines in the script are the imports, the _input = input()
and the decorators (because decorators are semantic sugar).
If what you want to do is to run a fn when you type a particular command, use a dict of fns instead:
def poo:
pass
fns = {"test":poo}
choice = None
while choice not in fns:
choice = input("Fn: ")
fn[choice]()
Note that there is nothing else wrong with your code, and you could just add calls to both fns at the end, if you are trying to test decorators, as a comment notes.
Decorators
Since there seems to be some disagreement about decorators, the following are equivalent:
@mydecorator(*args)
def fn():
pass
mydecorator(*args)(fn)
Perhaps this makes it clearer where the decorator code is called.
CodePudding user response:
If the question is: Why doesn't my program output 5
, then the answer is: because you don't call any of your functions.
The simplest solution to this particular problem is to just call the functions and let your decorator do the filtering it was designed for:
...
# code from the OP elided
poo()
foo()
Output:
test
5