Changes from the original
While adapting Peter Norvig’s lis.py for use in Fluent Python, Second Edition, I made a few changes for didactic reasons.
Luciano Ramalho
Major changes
- Make the
lambdaform accept more than one expression as the body. This is consistent with Scheme syntax, and provides a useful example for the book. To implement this:- In
Procedure.__call__: evaluateself.bodyas a list of expressions, instead of a single expression. Return the value of the last expression. - In
evaluate(): when processinglambda, unpack expression into(_, parms, *body), to accept a list of expressions as the body.
- In
- Remove the
global_envglobaldict. It is only used as a default value for theenvparameter inevaluate(), but it is unsafe to use mutable data structures as parameter default values. To implement this:- In
repl(): create local variableglobal_envand pass it as theenvparamater ofevaluate(). - In
evaluate(), removeglobal_envdefault value forenv.
- In
- Rewrite the custom test script lispytest.py as lis_test.py: a standard pytest test suite including new test cases, preserving all Norvig’s test cases for lis.py but removing the test cases for the features implemented only in lispy.py.
Minor changes
Cosmetic changes to make the code look more familiar to Python programmers, the audience of Fluent Python.
- Rename
eval()toevaluate(), to avoid confusion with Python’sevalbuilt-in function. - Refer to the list class as
listinstead of aliasing asList, to avoid confusion withtyping.Listwhich is often imported asList. - Import
collections.ChainMapasChainMapinstead ofEnvironment.
💬 评论