- Functional Python Programming
- Steven F. Lott
- 287字
- 2021-08-27 19:20:22
Pure functions
To be expressive, a function should be free from the confusion created by side effects. Using pure functions can also allow some optimizations by changing evaluation order. The big win, however, stems from pure functions being conceptually simpler and much easier to test.
To write a pure function in Python, we have to write local-only code. This means we have to avoid the global statements. We need to look closely at any use of nonlocal; while it is a side effect in some ways, it's confined to a nested function definition. This is an easy standard to meet. Pure functions are a common feature of Python programs.
There isn't a trivial way to guarantee a Python function is free from side effects. It is easy to carelessly break the pure function rule. If we ever want to worry about our ability to follow this rule, we could write a function that uses the dis module to scan a given function's __code__.co_code compiled code for global references. It could report on use of internal closures, and the __code__.co_freevarstuple method as well. This is a rather complex solution to a rare problem; we won't pursue it further.
A Python lambda is a pure function. While this isn't a highly recommended style, it's always possible to create pure functions through the lambda objects.
Here's a function created by assigning lambda to a variable:
>>> mersenne = lambda x: 2**x-1 >>> mersenne(17) 131071
We created a pure function using lambda and assigned this to the variable mersenne. This is a callable object with a single parameter, x, that returns a single value. Because lambdas can't have assignment statements, they're always pure functions and suitable for functional programming.
- Android Wearable Programming
- Learning Scala Programming
- Apache ZooKeeper Essentials
- Hands-On Machine Learning with scikit:learn and Scientific Python Toolkits
- C++ Builder 6.0下OpenGL編程技術
- 華為HMS生態與應用開發實戰
- Spring+Spring MVC+MyBatis整合開發實戰
- 數據結構習題解析與實驗指導
- .NET 3.5編程
- Android Wear Projects
- Advanced Express Web Application Development
- C++反匯編與逆向分析技術揭秘(第2版)
- Spring Boot+Vue全棧開發實戰
- PrimeFaces Blueprints
- Python函數式編程(第2版)