I'm creating a program making a "to do list". I prepared a function which writes a list of items entered by user. Then, using decorator, I want every item of the list to be added to txt file. I struggle with writing items of the lists one by one to the file. Using for loop in wrapper function doesn't work - nothing is shown on the log after running
def decorator(func):
def wrapper(*args):
with open("to_do_list.txt", "a") as l:
for i in range(len(args)):
l.write(f"{func(*args[i])} \n")
return wrapper
@decorator
def to_do():
print("TO DO LIST")
status = True
list = []
while status:
x = input("Add a task to a list: ")
list.append(x)
q = input("Do you wanna continue typing (Y), or quit (Q)?").lower()
if q == "n":
status = False
return list
to_do()
CodePudding user response:
This shouldn't be done with a decorator. Define an ordinary function that writes a list to the file, then call that with the returned value.
def write_list_to_file(l, filename):
with open(filename, 'a') as f:
for item in l:
f.write(item '\n'))
write_list_to_file(to_do(), "to_do_list.txt")
CodePudding user response:
If you want to fix the generator:
def decorator(func):
def wrapper(*args, **kwargs): # use args and kwargs
res = func(*args, **kwargs)
with open("to_do_list.txt", "a") as l:
# no need to iterate over the arguments
l.write(f"{res} \n")
return res
return wrapper
@decorator
def to_do():
print("TO DO LIST")
status = True
list = []
while status:
x = input("Add a task to a list: ")
list.append(x)
q = input("Do you wanna continue typing (Y), or quit (Q)?").lower()
if q == "n":
status = False
return list
to_do()
You should ask yourself if a decorator is what you want to use, since as mentioned in the comments under Barmar's answer, you wouldn't be able to not execute this just function (you could add parameters to the decorator, but as said, ask yourself is this is the easiest solution).