DiffSK / configobj

Python 3+ compatible port of the configobj library

Home Page:https://configobj.readthedocs.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to convert strings to int?

patrickvonplaten opened this issue · comments

Let's say we write the following code into the a file called "file.config":

[section1]
int=5
string='hallo'

and we then parse it using configObj

config = ConfigObj('file.config')
The created dictionaly will be as follows:
config: {'section1': {'int':'5', 'string':'hallo'}}

How can one convert all integer strings to int?
There is no simple example in the doc that explains it.
I did not manage to use the validation method to do this transformation.
is there an easy way?

@patrickvonplaten Here's a short example similar to how we do it at CLI Helpers:

file.config (the user's file):

[section1]
int=5
string='hallo'

file.configspec (the default/spec config):

[section1]
int=integer()
string=string()

The code example:

>>> import configobj
>>> import validate

>>> configspec = configobj.ConfigObj('file.configspec')
>>> config = configobj.ConfigObj('file.config', configspec=configspec)
>>> config.validate(validate.Validator())
True
>>> type(config['section1']['int'])
<class 'int'>
>>> config['section1']['int']
5