Skip to content

Instantly share code, notes, and snippets.

@kachayev
Created April 3, 2013 15:43
Show Gist options
  • Select an option

  • Save kachayev/5302369 to your computer and use it in GitHub Desktop.

Select an option

Save kachayev/5302369 to your computer and use it in GitHub Desktop.
Can you guess how it's possible? (yes, this is python)
>>> (let (a=2, b=4) (a + b))
6
>>> (let (x=20, y=40, z=1) (x*y*z))
800
@alexsv

alexsv commented Apr 3, 2013

Copy link
Copy Markdown

def let(**kwargs):
..globals().update(kwargs)
..def f(v):
....return v
..return f

@nhoad

nhoad commented Apr 3, 2013

Copy link
Copy Markdown
import sys

class let(object):
    def __init__(self, **kwargs):
        self.f_locals = f_locals = sys._getframe().f_back.f_locals
        self.orig_locals = dict(f_locals)
        f_locals.update(kwargs)

    def __call__(self, expr):
        return expr

    def __del__(self):
        self.f_locals.clear()
        self.f_locals.update(self.orig_locals)

assert (let (a=2, b=4) (a+b) ) == 6
assert (let (x=20, y=40, z=1) (x*y*z)) == 800

@kachayev

kachayev commented Apr 3, 2013

Copy link
Copy Markdown
Author

@nathan-hoad Good job!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment