intermediatePython
intermediatePython copied to clipboard
The subclass of email_logit in the decorator section has a problem
Hi all,
the last subclass "email_logit" in the decorator section didn't produce the right result. decorator
Usage:
@email_logit
def myfunc1():
pass
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in __init__
TypeError: __init__() missing 1 required positional argument: 'func'
I also encountered this problem. Is there someone knows what causes that?
Yes, this is the problem, because arguments should be passed in a different way for init functions, here is the fixed version:
class logit(object):
_logfile = 'out.log'
def __init__(self, func, *args):
self.func = func
def __call__(self, *args, **kwargs):
log_string = self.func.__name__ + " was called"
print(log_string)
with open(self._logfile, 'a') as opened_file:
opened_file.write(log_string + '\n')
# Now, send a notification
self.notify()
# return base func
return self.func(*args, **kwargs)
def notify(self):
# logit only logs, no more
pass
class email_logit(logit):
""" A logit implementation for sending emails to admins
when the function is called.
"""
def __init__(self, *args, email='[email protected]', **kwargs):
self.email = email
super(email_logit, self).__init__(*args, **kwargs)
def notify(self):
print('Sending email to {0}'.format(self.email))
@email_logit
def my_func(a=None):
print(a)
# Run the code:
my_func(3)
And here is another fix for the same issue https://github.com/yasoob/intermediatePython/pull/222