如何在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
相关产品推荐
相关产品推荐

