Home > OS >  Map ConfigParser dictionary to a class constructor with correct value types
Map ConfigParser dictionary to a class constructor with correct value types

Time:03-31

I have a config ini file which looks like below:

[user]
name=john
sex=male
age=19
income=2345.99

And I have a Python class called User with __init__ constructor below:

class User:
    def __init__(self, name: str, sex: str, age: int, income: float):
        self.__name = name
        self.__sex = sex
        self.__age = age
        self.__income = income

When I use ConfigParser to read the ini file & pass the configparser dictionary to the User constructor, the values in the dictionary are string.

config = ConfigParser()
config.read('test.ini')
user = User(**config["user"])

ConfigParser has methods like getfloat, getint, getboolean. I could use those methods & get the correct data type for each parameter.

However, this would require me to pass each parameter to the User constructor. It can be troublesome whenever I need to add/remove parameter for the User constructor

Is there anyway to use user = User(**config["user"]) in the constructor & configure ConfigParser to translate the value to correct data types?

Thanks.

CodePudding user response:

This becomes trivial if you use something like pydantic:

import pydantic
import configparser


class User(pydantic.BaseModel):
    name: str
    sex: str
    age: int
    income: float


config = configparser.ConfigParser()
with open("config.ini") as fd:
    config.read_file(fd)

user = User(**config["user"])

At this point, the string values from the config file have been converted into the appropriate data types:

>>> type(user.income)
<class 'float'>
  • Related