You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中为MySQLConnection添加类型注解?

解决mysql.connector类型注解中MySQLConnection未定义的问题

出现这个错误是因为MySQLConnection类型未被导入到当前代码的作用域中,以下是几种正确的注解方式:

方式一:显式导入MySQLConnection类型

直接从mysql.connector.connection模块导入MySQLConnection,同时可导入游标类型MySQLCursor:

from mysql.connector.connection import MySQLConnection
from mysql.connector.cursor import MySQLCursor
import mysql.connector

def get_db() -> tuple[MySQLConnection, MySQLCursor]:
    cnx: MySQLConnection = mysql.connector.connect(user='root', password='toor', host='127.0.0.1')
    cursor = cnx.cursor()
    return cnx, cursor

方式二:使用全限定类型名

如果不想单独导入类型,可直接使用完整的模块路径作为注解:

import mysql.connector

def get_db() -> tuple[mysql.connector.connection.MySQLConnection, mysql.connector.cursor.MySQLCursor]:
    cnx: mysql.connector.connection.MySQLConnection = mysql.connector.connect(user='root', password='toor', host='127.0.0.1')
    cursor = cnx.cursor()
    return cnx, cursor

方式三:使用字符串类型注解(Python 3.7+)

如果不想提前导入类型,或存在潜在循环引用问题,可用字符串包裹类型名。Python 3.7及以上版本支持这种写法,也可通过from __future__ import annotations让解释器自动解析字符串注解:

基础写法

import mysql.connector

def get_db() -> tuple["MySQLConnection", "MySQLCursor"]:
    cnx: "MySQLConnection" = mysql.connector.connect(user='root', password='toor', host='127.0.0.1')
    cursor = cnx.cursor()
    return cnx, cursor

配合from __future__ import annotations(推荐)

from __future__ import annotations
import mysql.connector

def get_db() -> tuple[MySQLConnection, MySQLCursor]:
    cnx: MySQLConnection = mysql.connector.connect(user='root', password='toor', host='127.0.0.1')
    cursor = cnx.cursor()
    return cnx, cursor

内容的提问来源于stack exchange,提问作者user21138890

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 06:18:08