0

My code (Python 3.11.4, mypy==1.4.1, pyMySQL==1.1.0)

import pymysql

db_info = {
    'host': 'example.com',
    'port': '3306',
    'user': 'admin',
    'password': 'admin',
    'database': 'test',
    'ssl_ca': '/path/to/ca',
    'charset': 'utf8'
}
conn = pymysql.connect(**db_info)
> mypy .\tmp.py --strict
tmp.py:12: error: No overload variant of "Connection" matches argument type "dict[str, str]"  [call-overload]
tmp.py:12: note: Possible overload variants:
tmp.py:12: note:     def [_C <: Cursor] __init__(self, *, host: str | None = ..., user: Any | None = ..., password: str = ..., database: Any | None = ..., port: int = ..., unix_socket: Any | None = ..., charset: str = ..., collation: str | None = ..., sql_mode: Any | None = ..., read_default_file: Any | None = ..., conv: Any = ..., use_unicode: bool | None = ..., client_flag: int = ..., cursorclass: None = ..., init_command: Any | None = ..., connect_timeout: int | None = ..., ssl: Mapping[Any, Any] | None = ..., ssl_ca: Any = ..., ssl_cert: Any = ..., ssl_disabled: Any = ..., ssl_key: Any = ..., ssl_verify_cert: Any = ..., ssl_verify_identity: Any = ..., read_default_group: Any | None = ..., compress: Any | None = ..., named_pipe: Any | None = ..., autocommit: bool | None = ..., db: Any | None = ..., passwd: Any | None = ..., local_infile: Any | None = ..., max_allowed_packet: int = ..., defer_connect: bool | None = ..., auth_plugin_map: Mapping[Any, Any] | None = ..., read_timeout: float | None = ..., write_timeout: float | None = ..., bind_address: Any | None = ..., binary_prefix: bool | None = ..., program_name: Any | None = ..., server_public_key: bytes | None = ...) -> Connection[Cursor]
tmp.py:12: note:     def [_C <: Cursor] __init__(self, *, host: str | None = ..., user: Any | None = ..., password: str = ..., database: Any | None = ..., port: int = ..., unix_socket: Any | None = ..., charset: str = ..., collation: str | None = ..., sql_mode: Any | None = ..., read_default_file: Any | None = ..., conv: Any = ..., use_unicode: bool | None = ..., client_flag: int = ..., cursorclass: type[_C] = ..., init_command: Any | None = ..., connect_timeout: int | None = ..., ssl: Mapping[Any, Any] | None = ..., ssl_ca: Any = ..., ssl_cert: Any = ..., ssl_disabled: Any = ..., ssl_key: Any = ..., ssl_verify_cert: Any = ..., ssl_verify_ident

I would like to use **db_info to pass arguments to pymysql.connect. However, mypy returns an error shown above.

I checked this question (Type annotations for *args and **kwargs), but this assumes defining a function by myself, so isn't useful in my case.

Is there a good way to resolve this error?

dmjy
  • 1,183
  • 3
  • 10
  • 26
  • 1
    Well, the port type does conflict with the function signature. The easiest would be to write a wrapper function that calls `connect` with dedicated named arguments. THen, in your code you can call the wrapper function with `**db_info`. – user2390182 Aug 08 '23 at 14:50

0 Answers0