函数式编程 偏函数 生成器 yeild checkpoint() 调试 反省
import inspect def checkpoint(): '''Instrumented `yield checkpoint()` goes here''' f = inspect.stack()[1].frame # stack[1] is the caller of checkpoint() return (f.f_lineno, { k: v for k, v in f.f_locals.items() if k != 'self' }) def f(): i,j=0,0 while True: i+=1 j+=100 yield checkpoint()import inspect def checkpoint(): '''Instrumented `yield checkpoint()` goes here''' f = inspect.stack()[1].frame # stack[1] is the caller of checkpoint() return (f.f_lineno, { k: v for k, v in f.f_locals.items() if k != 'self' }) def f(): i,j=0,0 while True: i+=1 j+=100 yield checkpoint()
函数栈 局部变量 代码行号 反省
>>> import inspect >>> >>> def checkpoint(): ... '''Instrumented `yield checkpoint()` goes here''' ... f = inspect.stack()[1].frame # stack[1] is the caller of checkpoint() ... return (f.f_lineno, { k: v for k, v in f.f_locals.items() if k != 'self' }) ... >>> def f(): ... i,j=0,0 ... while True: ... i+=1 ... j+=100 ... yield checkpoint() ... >>> g=f() >>> g.__next__() (6, {'i': 1, 'j': 100}) >>> g.__next__() (6, {'i': 2, 'j': 200}) >>> g.__next__() (6, {'i': 3, 'j': 300}) >>>
yeild checkpoint()
【理解并发程序执行 (Peterson算法、模型检验与软件自动化工具) [南京大学2022操作系统-P4]】https://www.bilibili.com/video/BV15T4y1Q76V
PC
状态机
函数调用了,函数返回了,状态还在
https://docs.python.org/zh-cn/3/library/inspect.html
inspect
--- 检查对象
源代码: Lib/inspect.py
inspect
模块提供了一些有用的函数帮助获取对象的信息,例如模块、类、方法、函数、回溯、帧对象以及代码对象。例如它可以帮助你检查类的内容,获取某个方法的源代码,取得并格式化某个函数的参数列表,或者获取你需要显示的回溯的详细信息。
该模块提供了4种主要的功能:类型检查、获取源代码、检查类与函数、检查解释器的调用堆栈。
类型和成员
getmembers()
函数获取对象的成员,例如类或模块。函数名以"is"开始的函数主要作为 getmembers()
的第2个参数使用。它们也可用于判定某对象是否有如下的特殊属性:
类型 |
属性 |
描述 |
---|---|---|
module -- 模块 |
__doc__ |
文档字符串 |
__file__ |
文件名(内置模块没有文件名) |
|
class -- 类 |
__doc__ |
文档字符串 |
__name__ |
类定义时所使用的名称 |
|
__qualname__ |
qualified name -- 限定名称 |
|
__module__ |
该类型被定义时所在的模块的名称 |
|
method -- 方法 |
__doc__ |
文档字符串 |
__name__ |
该方法定义时所使用的名称 |
|
__qualname__ |
qualified name -- 限定名称 |
|
__func__ |
实现该方法的函数对象 |
|
__self__ |
该方法被绑定的实例,若没有绑定则为 |
|
__module__ |
定义此方法的模块的名称 |
|
function -- 函数 |
__doc__ |
文档字符串 |
__name__ |
用于定义此函数的名称 |
|
__qualname__ |
qualified name -- 限定名称 |
|
__code__ |
包含已编译函数的代码对象 bytecode |
|
__defaults__ |
所有位置或关键字参数的默认值的元组 |
|
__kwdefaults__ |
保存仅关键字参数的所有默认值的映射 |
|
__globals__ |
此函数定义所在的全局命名空间 |
|
__builtins__ |
builtins 命名空间 |
|
__annotations__ |
参数名称到注解的映射;保留键 |
|
__module__ |
此函数定义所在的模块名称 |
|
traceback -- 回溯 |
tb_frame |
此层的帧对象 |
tb_lasti |
在字节码中最后尝试的指令的索引 |
|
tb_lineno |
当前行在 Python 源代码中的行号 |
|
tb_next |
下一个内部回溯对象(由本层调用) |
|
frame -- 帧 |
f_back |
下一个外部帧对象(此帧的调用者) |
f_builtins |
此帧执行时所在的 builtins 命名空间 |
|
f_code |
在此帧中执行的代码对象 |
|
f_globals |
此帧执行时所在的全局命名空间 |
|
f_lasti |
在字节码中最后尝试的指令的索引 |
|
f_lineno |
当前行在 Python 源代码中的行号 |
|
f_locals |
此帧所看到的局部命名空间 |
|
f_trace |
此帧的追踪函数,或``None`` |
|
code -- 代码 |
co_argcount |
参数数量(不包括仅关键字参数、* 或 ** 参数) |
co_code |
字符串形式的原始字节码 |
|
co_cellvars |
单元变量名称的元组(通过包含作用域引用) |
|
co_consts |
字节码中使用的常量元组 |
|
co_filename |
创建此代码对象的文件的名称 |
|
co_firstlineno |
第一行在Python源代码中的行号 |
|
co_flags |
|
|
co_lnotab |
编码的行号到字节码索引的映射 |
|
co_freevars |
自由变量的名字组成的元组(通过函数闭包引用) |
|
co_posonlyargcount |
仅限位置参数的数量 |
|
co_kwonlyargcount |
仅限关键字参数的数量(不包括 ** 参数) |
|
co_name |
定义此代码对象的名称 |
|
co_names |
除参数和函数局部变量之外的名称元组 |
|
co_nlocals |
局部变量的数量 |
|
co_stacksize |
需要虚拟机堆栈空间 |
|
co_varnames |
参数名和局部变量的元组 |
|
generator -- 生成器 |
__name__ |
名称 |
__qualname__ |
qualified name -- 限定名称 |
|
gi_frame |
frame -- 帧 |
|
gi_running |
生成器在运行吗? |
|
gi_code |
code -- 代码 |
|
gi_yieldfrom |
通过``yield from``迭代的对象,或``None`` |
|
coroutine -- 协程 |
__name__ |
名称 |
__qualname__ |
qualified name -- 限定名称 |
|
cr_await |
正在等待的对象,或``None`` |
|
cr_frame |
frame -- 帧 |
|
cr_running |
这个协程正在运行吗? |
|
cr_code |
code -- 代码 |
|
cr_origin |
协程被创建的位置,或``None``。参见 |
|
builtin |
__doc__ |
文档字符串 |
__name__ |
此函数或方法的原始名称 |
|
__qualname__ |
qualified name -- 限定名称 |
|
__self__ |
方法绑定到的实例,或``None`` |
在 3.5 版更改: 为生成器添加``__qualname__``和``gi_yieldfrom``属性。
生成器的``__name__``属性现在由函数名称设置,而不是代码对象名称,并且现在可以被修改。
在 3.7 版更改: 为协程添加``cr_origin``属性。
在 3.10 版更改: 为函数添加``__builtins__``属性。
inspect
— Inspect live objects
Source code: Lib/inspect.py
The inspect
module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.
There are four main kinds of services provided by this module: type checking, getting source code, inspecting classes and functions, and examining the interpreter stack.
Types and members
The getmembers()
function retrieves the members of an object such as a class or module. The functions whose names begin with “is” are mainly provided as convenient choices for the second argument to getmembers()
. They also help you determine when you can expect to find the following special attributes:
Type |
Attribute |
Description |
---|---|---|
module |
__doc__ |
documentation string |
__file__ |
filename (missing for built-in modules) |
|
class |
__doc__ |
documentation string |
__name__ |
name with which this class was defined |
|
__qualname__ |
qualified name |
|
__module__ |
name of module in which this class was defined |
|
method |
__doc__ |
documentation string |
__name__ |
name with which this method was defined |
|
__qualname__ |
qualified name |
|
__func__ |
function object containing implementation of method |
|
__self__ |
instance to which this method is bound, or |
|
__module__ |
name of module in which this method was defined |
|
function |
__doc__ |
documentation string |
__name__ |
name with which this function was defined |
|
__qualname__ |
qualified name |
|
__code__ |
code object containing compiled function bytecode |
|
__defaults__ |
tuple of any default values for positional or keyword parameters |
|
__kwdefaults__ |
mapping of any default values for keyword-only parameters |
|
__globals__ |
global namespace in which this function was defined |
|
__builtins__ |
builtins namespace |
|
__annotations__ |
mapping of parameters names to annotations; |
|
__module__ |
name of module in which this function was defined |
|
traceback |
tb_frame |
frame object at this level |
tb_lasti |
index of last attempted instruction in bytecode |
|
tb_lineno |
current line number in Python source code |
|
tb_next |
next inner traceback object (called by this level) |
|
frame |
f_back |
next outer frame object (this frame’s caller) |
f_builtins |
builtins namespace seen by this frame |
|
f_code |
code object being executed in this frame |
|
f_globals |
global namespace seen by this frame |
|
f_lasti |
index of last attempted instruction in bytecode |
|
f_lineno |
current line number in Python source code |
|
f_locals |
local namespace seen by this frame |
|
f_trace |
tracing function for this frame, or |
|
code |
co_argcount |
number of arguments (not including keyword only arguments, * or ** args) |
co_code |
string of raw compiled bytecode |
|
co_cellvars |
tuple of names of cell variables (referenced by containing scopes) |
|
co_consts |
tuple of constants used in the bytecode |
|
co_filename |
name of file in which this code object was created |
|
co_firstlineno |
number of first line in Python source code |
|
co_flags |
bitmap of |
|
co_lnotab |
encoded mapping of line numbers to bytecode indices |
|
co_freevars |
tuple of names of free variables (referenced via a function’s closure) |
|
co_posonlyargcount |
number of positional only arguments |
|
co_kwonlyargcount |
number of keyword only arguments (not including ** arg) |
|
co_name |
name with which this code object was defined |
|
co_names |
tuple of names other than arguments and function locals |
|
co_nlocals |
number of local variables |
|
co_stacksize |
virtual machine stack space required |
|
co_varnames |
tuple of names of arguments and local variables |
|
generator |
__name__ |
name |
__qualname__ |
qualified name |
|
gi_frame |
frame |
|
gi_running |
is the generator running? |
|
gi_code |
code |
|
gi_yieldfrom |
object being iterated by |
|
coroutine |
__name__ |
name |
__qualname__ |
qualified name |
|
cr_await |
object being awaited on, or |
|
cr_frame |
frame |
|
cr_running |
is the coroutine running? |
|
cr_code |
code |
|
cr_origin |
where coroutine was created, or |
|
builtin |
__doc__ |
documentation string |
__name__ |
original name of this function or method |
|
__qualname__ |
qualified name |
|
__self__ |
instance to which a method is bound, or |
Changed in version 3.5: Add __qualname__
and gi_yieldfrom
attributes to generators.
The __name__
attribute of generators is now set from the function name, instead of the code name, and it can now be modified.
Changed in version 3.7: Add cr_origin
attribute to coroutines.
Changed in version 3.10: Add __builtins__
attribute to functions.
高阶函数
# 高阶函数
def f(x):
return x * x
# map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
# map()传入的第一个参数是f,即函数对象本身。由于结果r是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。
r_lazy = map(f, [1, 2, 3]) # 惰性序列
r = list(r_lazy)
from functools import reduce
def add(x, y):
return x + y
r_reduce = reduce(add, [1, 4, 9])
def is_odd(n):
return n % 2 == 1
# 和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
r_lazy_1 = filter(is_odd, [1, 2, 3, 4])
r_1 = list(r_lazy_1)
偏函数
import functools
int2 = functools.partial(int, base=2)
def f(x, d=3):
return x ** d
f4 = functools.partial(f, d=4)
f2 = functools.partial(f, d=2)
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return t[1]
sorted(L, key=by_name)
L = [3, -5, 6, -89]
sorted(L, key=abs)
L = ['bob', 'about', 'Zoo', 'Credit']
sorted(L) # ['Credit', 'Zoo', 'about', 'bob']
sorted(L, key=str.lower) # ['about', 'bob', 'Credit', 'Zoo']
sorted - 廖雪峰的官方网站 https://www.liaoxuefeng.com/wiki/1016959663602400/1017408670135712
默认情况下,对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a'
,结果,大写字母Z
会排在小写字母a
的前面。