7

I am writing a config.ini file for my python project. I want to mention the standard date format of a column.

Something like this

prod_db_end_date   = 2017-01-01
prod_db_end_date_format = %Y-%m-%d

But it interpolates something else and errors out. Could someone please let me know how to use this?

Error traceback - File "C:\ProgramData\Anaconda3\lib\configparser.py", line 443, in _interpolate_some
      "found: %r" % (rest,))
configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%Y-%m-%d'
jdno
  • 4,104
  • 1
  • 22
  • 27
Nick M
  • 822
  • 1
  • 7
  • 20

1 Answers1

14

You have three options:

  • Disable interpolation, or pick a different interpolation handler. You can set the interpolation option to None to disable interpolation for the whole file:

    ConfigParse(interpolation=None)
    

    See the Interpolation of values section.

  • Access that specific value with interpolation disabled, setting raw=True for the ConfigParser.get() method:

    config.get('section', 'prod_db_end_date_format', raw=True)
    
  • Double the % characters to %%:

    prod_db_end_date_format = %%Y-%%m-%%d
    
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I'd appreciate very much if you could _comment_ which is your preferred solution and why.. – gboffi Sep 12 '17 at 08:28
  • @gboffi that depends on what you need to achieve; there are pros and cons to each, weigh those against your specific usecases. – Martijn Pieters Sep 12 '17 at 08:33
  • If I use `interpolation=ExtendedInterpolation()` with `[GENERAL] config_date_format = %%Y-%%m-%%d` and `self.configuration['GENERAL'].get('config_date_format')` it doesn't substitute two `%%` into `%`. Have to use `.replace('%%', '%')` in `datetime.strptime` which seems hacky? – fpopic Jun 08 '20 at 06:44
  • 1
    @fpopic: `ExtendedInterpolation` doesn't treat `%` as special at all, it uses a different format for interpolation. There `$` is special, and you'd have to use `$$` to get a literal dollar sign. You can just store `config_date_format = %Y-%m-%d`. This is covered in the [relevant section of the documentation](https://docs.python.org/3/library/configparser.html#configparser.ExtendedInterpolation), see the `[Escape]` section of the example, and contrast that with the [`BasicInterpolation` section](https://docs.python.org/3/library/configparser.html#configparser.BasicInterpolation) right above it. – Martijn Pieters Jun 18 '20 at 19:04