I want to convert the following code:
... urls = [many urls] links = [] funcs = [] for url in urls: func = getFunc(url, links) funcs.append(func) ... def getFunc(url, links): def func(): page = open(url) link = searchForLink(page) links.append(link) return func
in a much more convenient code:
urls = [many urls] links = [] funcs = [] for url in urls: <STATEMENT>(funcs): page = open(url) link = searchForLink(page) links.append(link)
I was hoping to do this with the with statement. As I commented below, I was hoping to achieve:
def __enter__(): def func(): ..code in the for loop.. def __exit__(): funcs.append(func)
Of course, this does not work.
List enumerations are not suitable for cases when the searchForLink action is not only one function, but also many functions. This would turn into extremely unreadable code. For example, even this would be problematic with a list:
for url in urls: page = open(url) link1 = searchForLink(page) link2 = searchForLink(page) actionOnLink(link1) actionOnLink(link2) .... many more of these actions... links.append(link1)
source share