进阶
前面都能读日常脚本了。下面几样出现频率低一些,但读编排代码会碰到。
lambda
只能写一个表达式,≈ JS 单行箭头函数。
python
lambda e: e["title"]
.validate(lambda output, _context: (
isinstance(output.get("brief"), str)
and output["brief"].strip() != ""
))js
;(e) =>
e.title.validate(
(output, _context) =>
typeof output?.brief === 'string' && output.brief.trim() !== '',
)| Python | JavaScript |
|---|---|
lambda 参数: 表达式 | (参数) => 表达式 |
isinstance(x, str) | typeof x === "string" |
isinstance(x, list) | Array.isArray(x) |
_context | 声明了但不用 |
工厂闭包
内层函数能读外层变量,用来「同一套逻辑、不同下标」。
python
def make_extract_node(segment_index: int):
async def extract_one(state: MeetingState) -> MeetingUpdate:
payload = state["segments"][segment_index]
return {...}
return extract_onejs
function makeExtractNode(segmentIndex) {
return async function extractOne(state) {
const payload = state.segments[segmentIndex]
return { ... }
}
}装饰器 @
python
@flow.chunk
async def split_segments(data):
...等价于:
python
async def split_segments(data):
...
split_segments = flow.chunk(split_segments)js
const splitSegments = flow.chunk(async function splitSegments(data) { ... })多个 @a @b 从下往上包。@ 是 Python 语法;flow.chunk 是框架 API。
argparse 开关
python
parser = argparse.ArgumentParser()
parser.add_argument("--real", action="store_true")
args = parser.parse_args()
output = asyncio.run(run_real()) if args.real else run_offline()js
const real = process.argv.includes('--real')
const output = real ? await runReal() : runOffline()action="store_true":写了 --real 就是 True,没写就是 False。
TypedDict / Annotated
描述 dict 的键,运行时仍是普通 dict。给类型检查器和 LangGraph 用。
python
class MeetingState(TypedDict):
segments: list[dict[str, Any]]
timeline: Annotated[list[str], operator.add]
final_minutes: NotRequired[dict[str, Any]]
class MeetingUpdate(TypedDict, total=False):
timeline: list[str]ts
type MeetingState = {
segments: Record<string, any>[]
timeline: string[]
final_minutes?: Record<string, any>
}
type MeetingUpdate = Partial<{
timeline: string[]
}>| Python | TypeScript |
|---|---|
TypedDict | 描述对象键,不是 class |
total=False | Partial<> |
NotRequired[T] | key?: T |
Annotated[list, operator.add] | 类型 + 合并策略(图状态用 + 拼 list) |
类方法里的 self
python
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
path = self.path.rstrip("/") or "/"
if path in ("/", "/index.html"):
returnjs
class Handler {
doGET() {
const path = this.path.replace(/\/$/, '') || '/'
if (['/', '/index.html'].includes(path)) return
}
}self 要显式写在第一个参数;JS 是 this。
易混清单(从头到尾)
True/False/Nonevstrue/false/nulland or notvs&& || !A if c else Bvsc ? A : B.get(k, default)vs?./??"\n".join(list)vslist.join("\n")- 推导式 ≈
map+filter;副作用用for len/append/invslength/push/includes- 切片用
slice,不要对照splice - 顶层 async 要
asyncio.run Path / "a"vspath.join- 可变默认用
default_factory,别写={} - dataclass 能构造;Pydantic 还能校验
async for≈for await;create_task先跑再等@decorator≈fn = decorator(fn)