I was asked to build two decorators: One of them is reading all the files in directory and her subs, and returns the files names that are matching the patterns it gets as arguments. It returns them as "files" argument to the wrapped function.
The second gets a list of files and returns a dict which the keys are the files names, and the values are the files content.
I did all I have been asked until here.
The next part of the question is to pass the files from the first generator to the second, and to do the second parameters optional - I mean, if the second decorated with the first, it shouldn't get any parameters in the second decorator, and get the files list from the first. Here i stuck.
that's the decorators :
The first:
from pathlib import Path
import fnmatch
import os
import glob
def find(*args):
def inner(f):
files = []
def wrapper(*wrapper_args, **kwargs):
p = Path("./")
for folder in p.glob("**"):
for file in os.listdir(folder):
for arg in args:
if fnmatch.fnmatch(file, arg):
files.append(file)
return f(files=files, *wrapper_args, **kwargs)
return wrapper()
return inner
@find("*.py", "*.txt")
def file_printer(files):
print(files)
The second:
def read_file(path):
with open(path, "r") as f:
f = f.read()
return f
def use(**use_kwargs):
def inner(f):
content = {}
def wrapper(*wrapper_args, **kwargs):
p = Path("./")
for folder in p.glob("**"):
for file in use_kwargs.get("files"):
if file in os.listdir(folder):
file_path = f"{folder}/{file}"
content[file_path] = read_file(file_path)
return f(content=content, *wrapper_args, **kwargs)
return wrapper()
return inner
@use(files=["cat.py", "dog.py"])
def file_printer(content):
print(content)
And it should work in this case too, and pass the "files" argument from the first to the second. Here I need your help.
@find("*.py", "*.txt")
@use
def file_printer(content):
print(content)