Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map ConfigParser dictionary to a class constructor with correct value types

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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'>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading