從Node.js+TypeScript無縫切換到Python的完整過程實(shí)錄
前言
隨著技術(shù)的發(fā)展和業(yè)務(wù)需求的變化,團(tuán)隊(duì)可能會(huì)面臨從一種技術(shù)棧遷移到另一種技術(shù)棧的情況。本文檔旨在幫助熟悉 Node.js + TypeScript 生態(tài)的開發(fā)者快速適應(yīng)和掌握 Python 開發(fā),特別是在本項(xiàng)目從 JavaScript/TypeScript 技術(shù)棧轉(zhuǎn)向 Python 技術(shù)棧的過程中提供指導(dǎo)和參考。
通過本文檔的閱讀,您將收獲:
- Node.js + TypeScript 與 Python 在語(yǔ)法和概念上的對(duì)應(yīng)關(guān)系
- 異步編程在兩種語(yǔ)言中的實(shí)現(xiàn)方式對(duì)比
- 模塊導(dǎo)入和包管理機(jī)制的差異
- 面向?qū)ο缶幊痰牟煌瑢?shí)現(xiàn)方式
- 類型系統(tǒng)和靜態(tài)檢查的差異
- 錯(cuò)誤處理機(jī)制的對(duì)比
- 項(xiàng)目實(shí)踐中需要注意的關(guān)鍵點(diǎn)
適用范圍
本文檔適用于:
- 熟悉 Node.js + TypeScript 開發(fā),需要快速上手 Python 項(xiàng)目的開發(fā)人員
- 希望了解 Node.js + TypeScript 與 Python 差異的技術(shù)負(fù)責(zé)人和架構(gòu)師
- 需要進(jìn)行技術(shù)棧遷移評(píng)估的項(xiàng)目經(jīng)理
具體方案
1. 語(yǔ)法基礎(chǔ)對(duì)比
變量聲明與類型系統(tǒng)
Node.js + TypeScript 是靜態(tài)類型語(yǔ)言,而 Python 是動(dòng)態(tài)類型語(yǔ)言。盡管 Python 3.5+ 支持類型提示,但它仍然在運(yùn)行時(shí)進(jìn)行類型檢查。
const name: string = "張三"; const age: number = 25; const isActive: boolean = true; const hobbies: string[] = ["讀書", "游泳"];
name: str = "張三" age: int = 25 is_active: bool = True # 注意:Python 使用 snake_case 命名規(guī)范 hobbies: List[str] = ["讀書", "游泳"] # 需要從 typing 導(dǎo)入 List
注意:Python 推薦使用 snake_case 命名法,而 TypeScript 更常用 camelCase。
函數(shù)定義
function greet(name: string): string {
return `Hello, ${name}!`;
}
// 箭頭函數(shù)
const greet = (name: string): string => {
return `Hello, ${name}!`;
};def greet(name: str) -> str:
return f"Hello, {name}!"
# Lambda 函數(shù)
greet = lambda name: f"Hello, {name}!"2. 異步編程對(duì)比
這是 Node.js + TypeScript 和 Python 最重要的區(qū)別之一。Node.js 天生就是為異步 I/O 設(shè)計(jì)的,而 Python 通過 asyncio 模塊提供了類似能力。
Node.js + TypeScript 異步編程
// Promise 方式
function fetchData(): Promise<string> {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("數(shù)據(jù)獲取成功");
}, 1000);
});
}
// Async/await 方式
async function getData(): Promise<void> {
try {
const result: string = await fetchData();
console.log(result);
} catch (error) {
console.error(error);
}
}
Python 異步編程
import asyncio
from typing import Awaitable
async def fetch_data() -> str:
await asyncio.sleep(1) # 模擬異步操作
return "數(shù)據(jù)獲取成功"
async def get_data() -> None:
try:
result: str = await fetch_data()
print(result)
except Exception as e:
print(f"錯(cuò)誤: {e}")
# 運(yùn)行異步函數(shù)
asyncio.run(get_data())3. 模塊導(dǎo)入機(jī)制對(duì)比
Node.js 使用 CommonJS 或 ES6 模塊系統(tǒng),而 Python 有自己的模塊導(dǎo)入機(jī)制。
Node.js + TypeScript 模塊導(dǎo)入
// CommonJS
const fs = require('fs');
const myModule = require('./myModule');
// ES6 模塊
import fs from 'fs';
import { someFunction } from './myModule';
// TypeScript 中的類型導(dǎo)入
import type { SomeInterface } from './interfaces';Python 模塊導(dǎo)入
# Python 標(biāo)準(zhǔn)庫(kù)導(dǎo)入 import os import json from typing import Dict, List, Optional # 自定義模塊導(dǎo)入 from concat_model.service import default_concat_service from concat_model.types import Node, Workflow
在我們的項(xiàng)目中,可以看到復(fù)雜的導(dǎo)入路徑(兩層及以上),例如在 concat_model/core/llm_service.py 中:
import sys import os from typing import Dict, List, Any # 添加項(xiàng)目根目錄到Python路徑,以便正確導(dǎo)入chat_model sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) # 直接導(dǎo)入chat_model中的llm_service from search_rag_graph.chat_model.llm_service import llm_service as external_llm_service
4. 面向?qū)ο缶幊虒?duì)比

4. 類
Node.js + TypeScript 類定義
class Person {
private name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public greet(): string {
return `Hello, I'm ${this.name}`;
}
}Python 類定義
class Node:
"""節(jié)點(diǎn)類"""
def __init__(self, node_id: str, tag_key: str, action_type: str, action_target: str, pre_snapshot: Optional[Any] = None, **kwargs):
self.node_id = node_id
self.tag_key = tag_key
self.action_type = action_type
self.action_target = action_target
self.pre_snapshot = pre_snapshot
self.__dict__.update(kwargs)
def to_dict(self) -> Dict[str, Any]:
"""轉(zhuǎn)換為字典"""
return self.__dict__.copy()Python 也支持通過類型注解實(shí)現(xiàn)類似 TypeScript 的類型安全,但檢查是在編譯時(shí)而不是運(yùn)行時(shí)進(jìn)行的(除非使用 mypy 等工具)。
OOP 特性對(duì)比:
特性 | Node.js + TypeScript | Python |
構(gòu)造函數(shù) |
|
|
私有成員 |
關(guān)鍵字 |
(命名約定) |
方法參數(shù) | 直接使用 | 必須包含 作為第一個(gè)參數(shù) |
繼承語(yǔ)法 |
|
|
5. 類型系統(tǒng)對(duì)比
TypeScript 類型系統(tǒng)
interface User {
id: number;
name: string;
email?: string; // 可選屬性
}
// 泛型
interface ApiResponse<T> {
data: T;
status: number;
}
// 聯(lián)合類型
type Status = "pending" | "approved" | "rejected";
// 類型別名
type UserId = string | number;Python 類型系統(tǒng)
# Python 類型提示
from typing import Optional, Union, Dict, List, TypeVar, Generic
# 類似接口的概念(使用 Protocol,Python 3.8+)
from typing_extensions import Protocol
class User(Protocol):
id: int
name: str
email: Optional[str]
# 泛型
T = TypeVar('T')
class ApiResponse(Generic[T]):
def __init__(self, data: T, status: int):
self.data = data
self.status = status
# 聯(lián)合類型
from typing import Literal
Status = Literal["pending", "approved", "rejected"]
# 類型別名
UserId = Union[str, int]在我們的項(xiàng)目中,如 search_model/models.py 所示,廣泛使用了 Pydantic 進(jìn)行數(shù)據(jù)建模和驗(yàn)證:
class QueryFullFlowInput(BaseModel):
"""
查詢?nèi)鞒梯斎雲(yún)?shù)
"""
query_text: str = Field(..., description="查詢語(yǔ)句,描述業(yè)務(wù)意圖")
env_type: EnvironmentType = Field(..., description="環(huán)境類型,dev、test或prod")
form_params: Optional[List[str]] = Field(None, description="表單參數(shù)數(shù)組,可選")
version: Optional[str] = Field(None, description="版本約束,test、prod必填")這類似于 TypeScript 中使用接口定義數(shù)據(jù)結(jié)構(gòu)的方式。
6. 錯(cuò)誤處理機(jī)制對(duì)比

錯(cuò)誤處理對(duì)比:
特性 | Node.js + TypeScript | Python |
捕獲關(guān)鍵字 |
|
|
捕獲所有錯(cuò)誤 |
|
|
自定義錯(cuò)誤 | 繼承 類 | 繼承 類 |
堆棧跟蹤 |
|
模塊 |
7. 包管理和依賴管理

Node.js + TypeScript 包管理
Node.js 使用 npm 或 yarn 進(jìn)行包管理,依賴定義在 package.json 中:
{
"dependencies": {
"express": "^4.18.0",
"lodash": "^4.17.21"
},
"devDependencies": {
"typescript": "^4.9.0",
"ts-node": "^10.9.0"
}
}Python 包管理
Python 使用 pip 作為包管理工具,依賴通常定義在 requirements.txt 或 pyproject.toml 中。在我們的項(xiàng)目中,使用 pyproject.toml:
[project]
dependencies = [
"fastapi>=0.124.4",
"uvicorn>=0.38.0",
"requests>=2.31.0",
"chromadb>=0.4.24",
"jieba>=0.42.1",
"numpy>=1.26.4",
"pydantic>=2.5.3",
]
[build-system]
requires = ["setuptools>=42", "wheel"]
build-backend = "setuptools.build_meta"成果展示
通過采用這些最佳實(shí)踐,我們的項(xiàng)目實(shí)現(xiàn)了以下成果:
- 成功的技術(shù)棧遷移:從 JavaScript/TypeScript 生態(tài)順利過渡到 Python 生態(tài),保持了系統(tǒng)的穩(wěn)定性和可維護(hù)性。
- 統(tǒng)一的代碼風(fēng)格:通過遵循 Python 的編碼規(guī)范(如 PEP 8)和項(xiàng)目?jī)?nèi)部約定,保證了代碼的一致性。
- 高效的異步處理:利用 Python 的 asyncio 特性,在處理大量 I/O 操作時(shí)仍能保持良好的性能表現(xiàn)。
- 清晰的模塊結(jié)構(gòu):借鑒了 Node.js 的模塊化思想,在 Python 中實(shí)現(xiàn)了清晰的包和模塊組織結(jié)構(gòu)。
- 完善的類型系統(tǒng):通過使用 Python 的類型提示和 Pydantic 模型,提升了代碼的可讀性和可維護(hù)性。
- 完善的錯(cuò)誤處理機(jī)制:建立了健壯的異常處理體系,提高了系統(tǒng)的穩(wěn)定性。
- 強(qiáng)大的生態(tài)支持:充分利用 Python 在 AI、數(shù)據(jù)處理等領(lǐng)域的強(qiáng)大生態(tài)優(yōu)勢(shì)。
總結(jié)
從 Node.js + TypeScript 切換到 Python 并不僅僅是學(xué)習(xí)一門新語(yǔ)言,更是一種思維方式的轉(zhuǎn)變。以下是幾個(gè)關(guān)鍵要點(diǎn):
- 擁抱差異而非抵觸:兩種語(yǔ)言各有優(yōu)勢(shì),理解它們的設(shè)計(jì)哲學(xué)有助于更好地使用它們。TypeScript 提供了編譯時(shí)類型檢查,而 Python 提供了更靈活的運(yùn)行時(shí)行為。
- 漸進(jìn)式學(xué)習(xí):不需要完全忘記 Node.js + TypeScript 的經(jīng)驗(yàn),而是要學(xué)會(huì)如何將其中的優(yōu)秀思想(如模塊化、異步編程、類型安全)應(yīng)用到 Python 開發(fā)中。
- 重視工具鏈:Python 有著豐富的生態(tài)系統(tǒng),學(xué)會(huì)使用合適的工具(如 black 代碼格式化、mypy 類型檢查、pytest 測(cè)試框架等)能夠顯著提升開發(fā)效率。
- 關(guān)注性能特征:Python 在某些方面與 Node.js 有不同的性能特征,了解這些差異有助于編寫高性能的應(yīng)用程序。
- 利用生態(tài)優(yōu)勢(shì):Python 在數(shù)據(jù)科學(xué)、機(jī)器學(xué)習(xí)、AI 領(lǐng)域擁有強(qiáng)大的生態(tài)系統(tǒng),這是從 Node.js 切換到 Python 的重要價(jià)值之一。
- 持續(xù)學(xué)習(xí):技術(shù)在不斷發(fā)展,保持對(duì)新技術(shù)和最佳實(shí)踐的關(guān)注是每個(gè)開發(fā)者都應(yīng)該具備的素質(zhì)。
通過本文檔提供的對(duì)比和實(shí)踐建議,希望可以幫助您順利完成從 Node.js + TypeScript 到 Python 的過渡,并在新的技術(shù)棧中發(fā)揮出色的表現(xiàn)。
參考文檔
- Python 官方文檔
- Python 異步 IO 官方文檔
- FastAPI 文檔
- Node.js 官方文檔
- TypeScript 官方文檔
- PEP 8 - Python 代碼風(fēng)格指南
- Python 類型提示指南
- Pydantic 文檔
到此這篇關(guān)于從Node.js+TypeScript無縫切換到Python的文章就介紹到這了,更多相關(guān)Node.js TS無縫切換到Python內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Agent開發(fā)核心技術(shù)解析以及現(xiàn)代Agent架構(gòu)設(shè)計(jì)
解讀Tensorflow2.0訓(xùn)練損失值降低,但測(cè)試正確率基本不變的情況
Tensorflow訓(xùn)練模型越來越慢的2種解決方案
Python分支語(yǔ)句與循環(huán)語(yǔ)句應(yīng)用實(shí)例分析
Python?OpenCV中常用圖片處理函數(shù)小結(jié)
使用Django開發(fā)簡(jiǎn)單接口實(shí)現(xiàn)文章增刪改查
Python實(shí)現(xiàn)的幾個(gè)常用排序算法實(shí)例
python六種基本數(shù)據(jù)類型及常用函數(shù)展示

