Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I think it's an extraordinary strength of Python that I hadn't seen your code when writing mine but that other than two variable names they're identical. Leaving my comment up for demonstration of this.


Ha, awesome! I went for an exact transliteration although if I were to use this idea for real I would probably do the assignment explicitly in the body. I think this looks a bit more pythonic:

    @contextmanager
    def restoring(obj, attr):
        old_val = getattr(obj, attr)
        yield
        setattr(obj, attr, old_val)
    
    x.a = 1    
    with restoring(x, "a"):
       print x.a
       x.a = 2
       print x.a
    print x.a




Consider applying for YC's Winter 2027 batch! Applications are open till November 2.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: