Equivalent quote from python in lisp

In python, what is equivalent to a quote operator? I consider it necessary to postpone the assessment. For example, suppose in the following lisp psuedocode I have:

a = '(func, 'g) g = something (eval a) 

What I am doing is deferring the evaluation of g until a later time. This is necessary because I want to define g later. What is the equivalent idea of ​​this psuedocode in python?

+4
source share
2 answers
 a = lambda: func(g) g = something a() 

This is not quite a literal translation - the most literal translation will use string and eval - but this is probably best suited. The quote is probably not what you wanted in Lisp; you probably wanted to delay something or create lambda . Note that func and g are trailing variables in the lambda function, not characters, so if you call a from a different binding environment for func or g , it will still use the variables from a the definition environment.

+9
source

Using eval to delay evaluation is bad in both Lisp and Python.

in Python, and in Lisp you can defer evaluation using closure:

 def print_it(x): def f(): print g(x) return f f = print_it(42) def g(x): return x * x f() 

Note that what is locked is not the value of the variable, but the variable itself, and this is sometimes surprising:

 fa = [] for x in range(10): def g(): print x fa.append(g) for f in fa: f() # all of them will print 9 x = 42 fa[0]() # the output will be 42 

to solve this problem (which may also be present in Common Lisp), you can see things like:

 for x in range(10): def g(x = x): print x fa.append(g) 

or (in CL) things like

 (let ((aa)) (lambda () (print a))) 

Python also has a special lambda form for anonymous functions, but they are limited to one single expression and cannot contain any instruction. A locally def infected function is instead a regular function without any restrictions.

 for x in range(10): # print is a statement in Python 2.x and cannot be in a lambda fa.append(lambda x=x: sys.stdout.write(str(x) + "\n")) 

Finally, Python 2.x has a syntax limitation, and private variables are read-only, because if a function has an assignment (or extended assignment), there are only two possibilities:

  • The variable is global (and was previously declared using global x )
  • This variable is local

and, in particular, he ruled out that the assigned variable may be a local area of ​​the enclosing function.

Python 3.x eliminated this limitation by providing a new possible nonlocal x declaration, and now the well-known adder example can be implemented as

 def adder(x): def f(y): nonlocal x x += y return x return f 
+3
source

Source: https://habr.com/ru/post/1497308/


All Articles