I was curious on how decorators worked so was seeing if it would work for placing generic functions inside walking a path. I wanted to return the longest segment of integers in space seperated files below the path (and then return this value or possibly print it). Is this possible?
I tried to return things in countL with no success. Then was curious if I placed outside out of the function how this would work. Are Decorators only for printing or can you return from them to get this example to operate properly??
def walkPath(fn):
def wrapper(*args, **kwargs):
outside = None
for dirname, dirnames, filenames in os.walk(args[0]):
for filename in filenames:
fn(filename, dirname, outside, *args, **kwargs)
return wrapper
@walkPath
def countL(filename, dirname, outside, path, extension = '.wrd'):
if (filename[-4:] == extension):
with open(os.path.join(dirname, filename), 'r') as input:
data = input.readlines()
for i in range(len(data)):
temp = data[i].split()
if (int(temp[1]) - int(temp[0]) > longest):
outside = int(temp[1]) - int(temp[0])
This explains what I was doing without the decorator and then was just seeing if you could get the same functionality but making it generic. This means where it wasn’t necessarily the longest word in a set of files but maybe a set of files with the word ‘s’ in the filename for example. Just don’t know how to handle the external variable longest properly or if that is possible with decorators.
def countLength(path, extension = '.wrd'):
longest = 0
for dirname, dirnames, filenames in os.walk(path):
for filename in filenames:
if (filename[-4:] == extension):
with open(os.path.join(dirname, filename), 'r') as input:
data = input.readlines()
for i in range(len(data)):
temp = data[i].split()
if (int(temp[1]) - int(temp[0]) > longest):
longest = int(temp[1]) - int(temp[0])
return longest
You problem is, you are trying to split into the outer loop and its body, but within the loop you had a local variable (
longest) to compare the numbers. So what you would need to do is to make your inner function aggregate the results. That means the walkPath loop would need to save the result of every call tofnand hand it over to the next call, so you can do the comparison withinfn. At the end it should spit out what the last call returned. I guess this is what you were trying to do withoutside. I also removed thepathargument fromcountL, because it didn’t do anything. You example should work like this:You would then have to call something like
countL(0).