Type hints - am I doing it right?

Frank Millman frank at chagford.com
Wed Dec 13 02:19:16 EST 2023


Hi all

I am adding type hints to my code base.

I support three databases - sqlite3, Sql Server, PostgreSQL. The db 
parameters are kept in an ini file, under the section name 'DbParams'. 
This is read on program start, using configparser, and passed to a 
function config_database() in another module with the argument 
cfg['DbParams'].

In the other module I have this -

      def config_database(db_params):

To add a type hint, I now have this -

      def config_database(db_params: configparser.SectionProxy):

To get this to work, I have to add 'import configparser' at the top of 
the module.

I have three separate modules, one for each database, with a subclass 
containing the methods and attributes specific to that database. Each 
one has a connect() method which receives db_params as a parameter. Now 
I have to add 'import configparser' at the top of each of these modules 
in order to type hint the method.

This seems verbose. If it is the correct way of doing it I can live with 
it, but I wondered if there was an easier way.

BTW I have realised that I can bypass the problem by converting 
db_params to a dict, using dict(cfg['DbParams']). But I would still like 
an answer to the original question, as I am sure similar situations will 
occur without such a simple solution.

Thanks

Frank Millman



More information about the Python-list mailing list