Is there a Python equivalent of the Haskell 'let'

前端 未结 9 1265
青春惊慌失措
青春惊慌失措 2020-12-29 21:38

Is there a Python equivalent of the Haskell \'let\' expression that would allow me to write something like:

list2 = [let (name,size)=lookup(productId) in (ba         


        
9条回答
  •  青春惊慌失措
    2020-12-29 21:57

    class let:
        def __init__(self, var):
            self.x = var
    
        def __enter__(self):
            return self.x
    
        def __exit__(self, type, value, traceback):
            pass
    
    with let(os.path) as p:
        print(p)
    

    But this is effectively the same as p = os.path as p's scope is not confined to the with block. To achieve that, you'd need

    class let:
        def __init__(self, var):
            self.value = var
        def __enter__(self):
            return self
        def __exit__(self, type, value, traceback):
            del var.value
            var.value = None
    
    with let(os.path) as var:
        print(var.value)  # same as print(os.path)
    print(var.value)  # same as print(None)
    
    

    Here var.value will be None outside of the with block, but os.path within it.

提交回复
热议问题