Skip to content

进阶

前面都能读日常脚本了。下面几样出现频率低一些,但读编排代码会碰到。

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() !== '',
  )
PythonJavaScript
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_one
js
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[]
}>
PythonTypeScript
TypedDict描述对象键,不是 class
total=FalsePartial<>
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"):
            return
js
class Handler {
  doGET() {
    const path = this.path.replace(/\/$/, '') || '/'
    if (['/', '/index.html'].includes(path)) return
  }
}

self 要显式写在第一个参数;JS 是 this

易混清单(从头到尾)

  1. True/False/None vs true/false/null
  2. and or not vs && || !
  3. A if c else B vs c ? A : B
  4. .get(k, default) vs ?. / ??
  5. "\n".join(list) vs list.join("\n")
  6. 推导式 ≈ map + filter;副作用用 for
  7. len / append / in vs length / push / includes
  8. 切片用 slice,不要对照 splice
  9. 顶层 async 要 asyncio.run
  10. Path / "a" vs path.join
  11. 可变默认用 default_factory,别写 ={}
  12. dataclass 能构造;Pydantic 还能校验
  13. async forfor awaitcreate_task 先跑再等
  14. @decoratorfn = decorator(fn)