Type hints - am I doing it right?
Cameron Simpson
cs at cskk.id.au
Wed Dec 13 03:47:00 EST 2023
On 13Dec2023 09:19, Frank Millman <frank at chagford.com> wrote:
>I am adding type hints to my code base.
[...]
>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.
Not really. It's like any other name - it needs importing if you're
going to use it.
You can make the hint itself more compact:
from configparser import SectionProxy
.......
def config_database(db_params: SectionProxy):
Or you could be a bit more agnostic:
from typing import Mapping
.......
def config_database(db_params: Mapping):
since I imagine config_database() would accept any kind of mapping
(dicts, etc etc).
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Python-list
mailing list