[Tutor] List comp question

Michael Langford mlangford.cs03 at gtalumni.org
Sat Nov 3 15:39:13 CET 2007


I decided you probably should also have a cleanup function since garbage
collection won't work now unless you explicitly clean the function. This
approach works, and also works if you call the function again after you've
called cleanup (it just runs the function 1 more time, then again, returns
the cached result until you cleanup).

def func_once(func):
    "A decorator that runs a function only once."
    def decorated(*args, **kwargs):
        try:
            return decorated._once_result
        except AttributeError:
            decorated._once_result = func(*args, **kwargs)
            return decorated._once_result
    return decorated

def func_once_cleanup(func):
    del func._once_result

# Example, will only parse the document once
@func_once
def print_and_return_big_list():
    print "I'm the method you want to run once"
    return
[23,2342,234,234,234,24,654,687,54,9684,654,864981,651,849815,65498,1651,6984651,6541,654984,651,645]

if __name__=="__main__":
    print_and_return_big_list()
    print_and_return_big_list()
    print_and_return_big_list()
    print_and_return_big_list()
    print_and_return_big_list()

    func_once_cleanup(print_and_return_big_list)

    print_and_return_big_list(



On 11/2/07, Michael Langford <mlangford.cs03 at gtalumni.org> wrote:
>
> Decorate level2 with a decorator that caches:
>
>  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425445
>
>     --Michael
>
> On 11/1/07, Kent Johnson <kent37 at tds.net> wrote:
> >
> > I am building a list like this:
> >
> >      tree = []
> >      for top in tops:
> >          l2 = level2(top)
> >          if l2:
> >              tree.append((top, l2))
> >
> > I would really like to turn this into a list comprehension:
> >
> > tree = [ (top, level2(top)) for top in tops if level2(top) ]
> >
> > but the call to level2() is expensive enough that I don't want to repeat
> > it. Is there any way to do this or am I stuck with the (IMO ugly) loop
> > form?
> >
> > Kent
> >
> > who actually does have a question occasionally :-)
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
>
> --
> Michael Langford
> Phone: 404-386-0495
> Consulting: http://www.TierOneDesign.com/




-- 
Michael Langford
Phone: 404-386-0495
Consulting: http://www.TierOneDesign.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071103/db3ac9dc/attachment.htm 


More information about the Tutor mailing list