I am trying to write a decorator that gets a single arg, i.e
@Printer(1)
def f():
print 3
So, naively, I tried:
class Printer:
def __init__(self,num):
self.__num=num
def __call__(self,func):
def wrapped(*args,**kargs):
print self.__num
return func(*args,**kargs**)
return wrapped
This is ok, but it also works as a decorator receiving no args, i.e
@Printer
def a():
print 3
How can I prevent that?
Well, it’s already effectively prevented, in the sense that calling
a()doesn’t work.But to stop it as the function is defined, I suppose you’d have to change
__init__to check the type ofnum:I don’t know if this is really worth the bother, though. It already doesn’t work as-is; you’re really asking to enforce the types of arguments in a duck-typed language.