Search code examples
pythonperllisplvalue

Is it possible something like lvalue of perl or setf of lisp in python?


In lisp you can say:

(setf (aref a 1) 5)

In perl you can say:

substr( $string, $start, $stop ) =~ s/a/b/g

Is it possible something like this in python? I mean is it possible to use function result as a lvalue (as a target for assignment operation)?


Solution

  • No. Assigning to the result of a function call is specifically prohibited at the compiler level:

    >>> foo() = 3
      File "<stdin>", line 1
    SyntaxError: can't assign to function call
    

    There are however two special cases in the Python syntax:

    # Slice assignment
    a = [1,2,3,4]
    a[0:2] = 98, 99  # (a will become [98, 99, 3, 4])
    
    # Tuple assignment
    (x, y, z) = (10, 20, 30)
    

    Note also that in Python there is a statement/function duality and an assignment or an augmented assignment (+=, *= ...) is not just a normal operator, but a statement and has special rules.

    Moreover in Python there is no general concept of "pointer"... the only way to pass to a function a place where to store something is to pass a "setter" closure because to find an assignable place you need to use explicit names, indexing or you need to work with the instance dictionary if the place is an object instance member).

    # Pass the function foo where to store the result
    foo( lambda value : setattr(myObject, "member", value) )