configobj.txt 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992
  1. ==================================
  2. Reading and Writing Config Files
  3. ==================================
  4. ----------------------------------------
  5. ConfigObj 4 Introduction and Reference
  6. ----------------------------------------
  7. :Authors: Michael Foord, Nicola Larosa
  8. :Version: ConfigObj 4.7.2
  9. :Date: 2010/02/27
  10. :Homepage: `ConfigObj Homepage`_
  11. :PyPI Entry: `ConfigObj on PyPI <http://pypi.python.org/pypi/configobj/>`_
  12. :Development: `Google Code Homepage`_
  13. :License: `BSD License`_
  14. :Support: `Mailing List`_
  15. .. _Mailing List: http://lists.sourceforge.net/lists/listinfo/configobj-develop
  16. .. _Google Code Homepage: http://code.google.com/p/configobj/
  17. .. meta::
  18. :description: ConfigObj - a Python module for easy reading and writing of
  19. config files.
  20. :keywords: python, script, module, config, configuration, data, persistence,
  21. developer, configparser
  22. .. contents:: ConfigObj Manual
  23. .. sectnum::
  24. .. note::
  25. The best introduction to working with ConfigObj, including the powerful configuration validation system,
  26. is the article:
  27. * `An Introduction to ConfigObj <http://www.voidspace.org.uk/python/articles/configobj.shtml>`_
  28. Introduction
  29. ============
  30. **ConfigObj** is a simple but powerful config file reader and writer: an *ini
  31. file round tripper*. Its main feature is that it is very easy to use, with a
  32. straightforward programmer's interface and a simple syntax for config files.
  33. It has lots of other features though :
  34. * Nested sections (subsections), to any level
  35. * List values
  36. * Multiple line values
  37. * String interpolation (substitution)
  38. * Integrated with a powerful validation system
  39. - including automatic type checking/conversion
  40. - repeated sections
  41. - and allowing default values
  42. * When writing out config files, ConfigObj preserves all comments and the order of members and sections
  43. * Many useful methods and options for working with configuration files (like the 'reload' method)
  44. * Full Unicode support
  45. For support and bug reports please use the ConfigObj `Mailing List`_ or the issue tracker on the
  46. `Google Code Homepage`_.
  47. Downloading
  48. ===========
  49. The current version is **4.7.2**, dated 27th February 2010. ConfigObj 4 is
  50. stable and mature. We still expect to pick up a few bugs along the way though [#]_.
  51. You can get ConfigObj in the following ways :
  52. * configobj.py_ from Voidspace
  53. ConfigObj has no external dependencies. This file is sufficient to access
  54. all the functionality except Validation_.
  55. * configobj.zip_ from Voidspace
  56. This also contains validate.py_ and `this document`_.
  57. * validate.py_ from Voidspace
  58. Installing
  59. ----------
  60. ConfigObj has a source distribution `on PyPI <http://pypi.python.org/pypi/configobj/>`_. If you unzip
  61. the archive you can install it with::
  62. setup.py install
  63. Alternatively, you can install with easy install or pip::
  64. easy_install configobj
  65. Documentation
  66. -------------
  67. *configobj.zip* also contains `this document`_.
  68. * You can view `this document`_ online at the `ConfigObj Homepage`_.
  69. Development Version
  70. -------------------
  71. It is sometimes possible to get the latest *development version* of ConfigObj
  72. from the Subversion Repository maintained on the `Google Code Homepage`_.
  73. .. _configobj.py: http://www.voidspace.org.uk/downloads/configobj.py
  74. .. _configobj.zip: http://www.voidspace.org.uk/downloads/configobj-4.7.2.zip
  75. .. _validate.py: http://www.voidspace.org.uk/downloads/validate.py
  76. .. _this document:
  77. .. _configobj homepage: http://www.voidspace.org.uk/python/configobj.html
  78. ConfigObj in the Real World
  79. ===========================
  80. **ConfigObj** is widely used. Projects using it include:
  81. * `Bazaar <http://bazaar-ng.org>`_.
  82. Bazaar is a Python distributed {acro;VCS;Version Control System}.
  83. ConfigObj is used to read ``bazaar.conf`` and ``branches.conf``.
  84. * `Chandler <http://chandler.osafoundation.org/>`_
  85. A Python and `wxPython <http://www.wxpython.org>`_
  86. Personal Information Manager, being developed by the
  87. `OSAFoundation <http://www.osafoundation.org/>`_.
  88. * `matplotlib <http://matplotlib.sourceforge.net/>`_
  89. A 2D plotting library.
  90. * `IPython <http://ipython.scipy.org/moin/>`_
  91. IPython is an enhanced interactive Python shell. IPython uses ConfigObj in a module called 'TConfig' that combines it with enthought `Traits <http://code.enthought.com/traits/>`_: `tconfig <http://ipython.scipy.org/ipython/ipython/browser/ipython/branches/saw/sandbox/tconfig>`_.
  92. * `Elisa - the Fluendo Mediacenter <http://elisa.fluendo.com/>`_
  93. Elisa is an open source cross-platform media center solution designed to be simple for people not particularly familiar with computers.
  94. Getting Started
  95. ===============
  96. The outstanding feature of using ConfigObj is simplicity. Most functions can be
  97. performed with single line commands.
  98. Reading a Config File
  99. ---------------------
  100. The normal way to read a config file, is to give ConfigObj the filename :
  101. .. code-block:: python
  102. from configobj import ConfigObj
  103. config = ConfigObj(filename)
  104. You can also pass the config file in as a list of lines, or a ``StringIO``
  105. instance, so it doesn't matter where your config data comes from.
  106. You can then access members of your config file as a dictionary. Subsections
  107. will also be dictionaries.
  108. .. code-block:: python
  109. from configobj import ConfigObj
  110. config = ConfigObj(filename)
  111. #
  112. value1 = config['keyword1']
  113. value2 = config['keyword2']
  114. #
  115. section1 = config['section1']
  116. value3 = section1['keyword3']
  117. value4 = section1['keyword4']
  118. #
  119. # you could also write
  120. value3 = config['section1']['keyword3']
  121. value4 = config['section1']['keyword4']
  122. Writing a Config File
  123. ---------------------
  124. Creating a new config file is just as easy as reading one. You can specify a
  125. filename when you create the ConfigObj, or do it later [#]_.
  126. If you *don't* set a filename, then the ``write`` method will return a list of
  127. lines instead of writing to file. See the write_ method for more details.
  128. Here we show creating an empty ConfigObj, setting a filename and some values,
  129. and then writing to file :
  130. .. code-block:: python
  131. from configobj import ConfigObj
  132. config = ConfigObj()
  133. config.filename = filename
  134. #
  135. config['keyword1'] = value1
  136. config['keyword2'] = value2
  137. #
  138. config['section1'] = {}
  139. config['section1']['keyword3'] = value3
  140. config['section1']['keyword4'] = value4
  141. #
  142. section2 = {
  143. 'keyword5': value5,
  144. 'keyword6': value6,
  145. 'sub-section': {
  146. 'keyword7': value7
  147. }
  148. }
  149. config['section2'] = section2
  150. #
  151. config['section3'] = {}
  152. config['section3']['keyword 8'] = [value8, value9, value10]
  153. config['section3']['keyword 9'] = [value11, value12, value13]
  154. #
  155. config.write()
  156. .. caution::
  157. Keywords and section names can only be strings [#]_. Attempting to set
  158. anything else will raise a ``ValueError``.
  159. See `String Interpolation and List Values`_ for an important note on
  160. using lists in combination with `String Interpolation`_.
  161. Config Files
  162. ------------
  163. The config files that ConfigObj will read and write are based on the 'INI'
  164. format. This means it will read and write files created for ``ConfigParser``
  165. [#]_.
  166. Keywords and values are separated by an ``'='``, and section markers are
  167. between square brackets. Keywords, values, and section names can be surrounded
  168. by single or double quotes. Indentation is not significant, but can be
  169. preserved.
  170. Subsections are indicated by repeating the square brackets in the section
  171. marker. You nest levels by using more brackets.
  172. You can have list values by separating items with a comma, and values spanning
  173. multiple lines by using triple quotes (single or double).
  174. For full details on all these see `the config file format`_. Here's an example
  175. to illustrate::
  176. # This is the 'initial_comment'
  177. # Which may be several lines
  178. keyword1 = value1
  179. 'keyword 2' = 'value 2'
  180. [ "section 1" ]
  181. # This comment goes with keyword 3
  182. keyword 3 = value 3
  183. 'keyword 4' = value4, value 5, 'value 6'
  184. [[ sub-section ]] # an inline comment
  185. # sub-section is inside "section 1"
  186. 'keyword 5' = 'value 7'
  187. 'keyword 6' = '''A multiline value,
  188. that spans more than one line :-)
  189. The line breaks are included in the value.'''
  190. [[[ sub-sub-section ]]]
  191. # sub-sub-section is *in* 'sub-section'
  192. # which is in 'section 1'
  193. 'keyword 7' = 'value 8'
  194. [section 2] # an inline comment
  195. keyword8 = "value 9"
  196. keyword9 = value10 # an inline comment
  197. # The 'final_comment'
  198. # Which also may be several lines
  199. ConfigObj specifications
  200. ========================
  201. .. code-block:: python
  202. config = ConfigObj(infile=None, options=None, configspec=None, encoding=None,
  203. interpolation=True, raise_errors=False, list_values=True,
  204. create_empty=False, file_error=False, stringify=True,
  205. indent_type=None, default_encoding=None, unrepr=False,
  206. write_empty_values=False, _inspec=False)
  207. Many of the keyword arguments are available as attributes after the config file has been
  208. parsed.
  209. .. note::
  210. New in ConfigObj 4.7.0: Instantiating ConfigObj with
  211. an ``options`` dictionary is now deprecated. To modify code that used to
  212. do this simply unpack the dictionary in the constructor call:
  213. .. code-block:: python
  214. config = ConfigObj(filename, **options)
  215. ConfigObj takes the following arguments (with the default values shown) :
  216. * infile: ``None``
  217. You don't need to specify an infile. If you omit it, an empty ConfigObj will be
  218. created. ``infile`` *can* be :
  219. * Nothing. In which case the ``filename`` attribute of your ConfigObj will be
  220. ``None``. You can set a filename at any time.
  221. * A filename. What happens if the file doesn't already exist is determined by
  222. the options ``file_error`` and ``create_empty``. The filename will be
  223. preserved as the ``filename`` attribute. This can be changed at any time.
  224. * A list of lines. Any trailing newlines will be removed from the lines. The
  225. ``filename`` attribute of your ConfigObj will be ``None``.
  226. * A ``StringIO`` instance or file object, or any object with a ``read`` method.
  227. The ``filename`` attribute of your ConfigObj will be ``None`` [#]_.
  228. * A dictionary. You can initialise a ConfigObj from a dictionary [#]_. The
  229. ``filename`` attribute of your ConfigObj will be ``None``. All keys must be
  230. strings. In this case, the order of values and sections is arbitrary.
  231. * 'raise_errors': ``False``
  232. When parsing, it is possible that the config file will be badly formed. The
  233. default is to parse the whole file and raise a single error at the end. You
  234. can set ``raise_errors = True`` to have errors raised immediately. See the
  235. exceptions_ section for more details.
  236. Altering this value after initial parsing has no effect.
  237. * 'list_values': ``True``
  238. If ``True`` (the default) then list values are possible. If ``False``, the
  239. values are not parsed for lists.
  240. If ``list_values = False`` then single line values are not quoted or
  241. unquoted when reading and writing.
  242. Changing this value affects whether single line values will be quoted or
  243. not when writing.
  244. * 'create_empty': ``False``
  245. If this value is ``True`` and the file specified by ``infile`` doesn't
  246. exist, ConfigObj will create an empty file. This can be a useful test that
  247. the filename makes sense: an impossible filename will cause an error.
  248. Altering this value after initial parsing has no effect.
  249. * 'file_error': ``False``
  250. If this value is ``True`` and the file specified by ``infile`` doesn't
  251. exist, ConfigObj will raise an ``IOError``.
  252. Altering this value after initial parsing has no effect.
  253. * 'interpolation': ``True``
  254. Whether string interpolation is switched on or not. It is on (``True``) by
  255. default.
  256. You can set this attribute to change whether string interpolation is done
  257. when values are fetched. See the `String Interpolation`_ section for more details.
  258. New in ConfigObj 4.7.0: Interpolation will also be done in list values.
  259. * 'configspec': ``None``
  260. If you want to use the validation system, you supply a configspec. This is
  261. effectively a type of config file that specifies a check for each member.
  262. This check can be used to do type conversion as well as check that the
  263. value is within your required parameters.
  264. You provide a configspec in the same way as you do the initial file: a
  265. filename, or list of lines, etc. See the validation_ section for full
  266. details on how to use the system.
  267. When parsed, every section has a ``configspec`` with a dictionary of
  268. configspec checks for *that section*.
  269. * 'stringify': ``True``
  270. If you use the validation scheme, it can do type checking *and* conversion
  271. for you. This means you may want to set members to integers, or other
  272. non-string values.
  273. If 'stringify' is set to ``True`` (default) then non-string values will
  274. be converted to strings when you write the config file. The validation_
  275. process converts values from strings to the required type.
  276. If 'stringify' is set to ``False``, attempting to set a member to a
  277. non-string value [#]_ will raise a ``TypeError`` (no type conversion is
  278. done by validation).
  279. * 'indent_type': ``' '``
  280. Indentation is not significant; it can however be present in the input and
  281. output config. Any combination of tabs and spaces may be used: the string
  282. will be repeated for each level of indentation. Typical values are: ``''``
  283. (no indentation), ``' '`` (indentation with four spaces, the default),
  284. ``'\t'`` (indentation with one tab).
  285. If this option is not specified, and the ConfigObj is initialised with a
  286. dictionary, the indentation used in the output is the default one, that is,
  287. four spaces.
  288. If this option is not specified, and the ConfigObj is initialised with a
  289. list of lines or a file, the indentation used in the first indented line is
  290. selected and used in all output lines. If no input line is indented, no
  291. output line will be either.
  292. If this option *is* specified, the option value is used in the output
  293. config, overriding the type of indentation in the input config (if any).
  294. * 'encoding': ``None``
  295. By default **ConfigObj** does not decode the file/strings you pass it into
  296. Unicode [#]_. If you want your config file as Unicode (keys and members)
  297. you need to provide an encoding to decode the file with. This encoding will
  298. also be used to encode the config file when writing.
  299. You can change the encoding attribute at any time.
  300. Any characters in your strings that can't be encoded with the specified
  301. encoding will raise a ``UnicodeEncodeError``.
  302. .. note::
  303. ``UTF16`` encoded files will automatically be detected and decoded,
  304. even if ``encoding`` is ``None``.
  305. This is because it is a 16-bit encoding, and ConfigObj will mangle it
  306. (split characters on byte boundaries) if it parses it without decoding.
  307. * 'default_encoding': ``None``
  308. When using the ``write`` method, **ConfigObj** uses the ``encoding``
  309. attribute to encode the Unicode strings. If any members (or keys) have
  310. been set as byte strings instead of Unicode, these must first be decoded
  311. to Unicode before outputting in the specified encoding.
  312. ``default_encoding``, if specified, is the encoding used to decode byte
  313. strings in the **ConfigObj** before writing. If this is ``None``, then
  314. the Python default encoding (``sys.defaultencoding`` - usually ASCII) is
  315. used.
  316. For most Western European users, a value of ``latin-1`` is sensible.
  317. ``default_encoding`` is *only* used if an ``encoding`` is specified.
  318. Any characters in byte-strings that can't be decoded using the
  319. ``default_encoding`` will raise a ``UnicodeDecodeError``.
  320. * 'unrepr': ``False``
  321. The ``unrepr`` option reads and writes files in a different mode. This
  322. allows you to store and retrieve the basic Python data-types using config
  323. files.
  324. This uses Python syntax for lists and quoting. See `unrepr mode`_ for the
  325. full details.
  326. * 'write_empty_values': ``False``
  327. If ``write_empty_values`` is ``True``, empty strings are written as
  328. empty values. See `Empty Values`_ for more details.
  329. * '_inspec': ``False``
  330. Used internally by ConfigObj when parsing configspec files. If you are
  331. creating a ConfigObj instance from a configspec file you must pass True
  332. for this argument as well as ``list_values=False``.
  333. Methods
  334. -------
  335. The ConfigObj is a subclass of an object called ``Section``, which is itself a
  336. subclass of ``dict``, the builtin dictionary type. This means it also has
  337. **all** the normal dictionary methods.
  338. In addition, the following `Section Methods`_ may be useful :
  339. * 'restore_default'
  340. * 'restore_defaults'
  341. * 'walk'
  342. * 'merge'
  343. * 'dict'
  344. * 'as_bool'
  345. * 'as_float'
  346. * 'as_int'
  347. * 'as_list'
  348. Read about Sections_ for details of all the methods.
  349. .. hint::
  350. The *merge* method of sections is a recursive update.
  351. You can use this to merge sections, or even whole ConfigObjs, into each
  352. other.
  353. You would typically use this to create a default ConfigObj and then merge
  354. in user settings. This way users only need to specify values that are
  355. different from the default. You can use configspecs and validation to
  356. achieve the same thing of course.
  357. The public methods available on ConfigObj are :
  358. * 'write'
  359. * 'validate'
  360. * 'reset'
  361. * 'reload'
  362. write
  363. ~~~~~
  364. .. code-block:: python
  365. write(file_object=None)
  366. This method writes the current ConfigObj and takes a single, optional argument
  367. [#]_.
  368. If you pass in a file like object to the ``write`` method, the config file will
  369. be written to this. (The only method of this object that is used is its
  370. ``write`` method, so a ``StringIO`` instance, or any other file like object
  371. will work.)
  372. Otherwise, the behaviour of this method depends on the ``filename`` attribute
  373. of the ConfigObj.
  374. ``filename``
  375. ConfigObj will write the configuration to the file specified.
  376. ``None``
  377. ``write`` returns a list of lines. (Not ``'\n'`` terminated)
  378. First the 'initial_comment' is written, then the config file, followed by the
  379. 'final_comment'. Comment lines and inline comments are written with each
  380. key/value.
  381. validate
  382. ~~~~~~~~
  383. .. code-block:: python
  384. validate(validator, preserve_errors=False, copy=False)
  385. .. code-block:: python
  386. # filename is the config file
  387. # filename2 is the configspec
  388. # (which could also be hardcoded into your program)
  389. config = ConfigObj(filename, configspec=filename2)
  390. #
  391. from validate import Validator
  392. val = Validator()
  393. test = config.validate(val)
  394. if test == True:
  395. print 'Succeeded.'
  396. The validate method uses the `validate
  397. <http://www.voidspace.org.uk/python/validate.html>`__ module to do the
  398. validation.
  399. This method validates the ConfigObj against the configspec. By doing type
  400. conversion as well it can abstract away the config file altogether and present
  401. the config *data* to your application (in the types it expects it to be).
  402. If the ``configspec`` attribute of the ConfigObj is ``None``, it raises a
  403. ``ValueError``.
  404. If the stringify_ attribute is set, this process will convert values to the
  405. type defined in the configspec.
  406. The validate method uses checks specified in the configspec and defined in the
  407. ``Validator`` object. It is very easy to extend.
  408. The configspec looks like the config file, but instead of the value, you
  409. specify the check (and any default value). See the validation_ section for
  410. details.
  411. .. hint::
  412. The system of configspecs can seem confusing at first, but is actually
  413. quite simple and powerful. The best guide to them is this article on
  414. ConfigObj:
  415. * `An Introduction to ConfigObj`_
  416. The ``copy`` parameter fills in missing values from the configspec (default
  417. values), *without* marking the values as defaults. It also causes comments to
  418. be copied from the configspec into the config file. This allows you to use a
  419. configspec to create default config files. (Normally default values aren't
  420. written out by the ``write`` method.)
  421. As of ConfigObj 4.3.0 you can also pass in a ConfigObj instance as your
  422. configspec. This is especially useful if you need to specify the encoding of
  423. your configspec file. When you read your configspec file, you *must* specify
  424. ``list_values=False``. If you need to support hashes inside the configspec
  425. values then you must also pass in ``_inspec=True``. This is because configspec
  426. files actually use a different syntax to config files and inline comment support
  427. must be switched off to correctly read configspec files with hashes in the values.
  428. .. code-block:: python
  429. from configobj import ConfigObj
  430. configspec = ConfigObj(configspecfilename, encoding='UTF8',
  431. list_values=False, _inspec=True)
  432. config = ConfigObj(filename, configspec=configspec)
  433. Return Value
  434. ############
  435. By default, the validate method either returns ``True`` (everything passed)
  436. or a dictionary of ``True`` / ``False`` representing pass/fail. The dictionary
  437. follows the structure of the ConfigObj.
  438. If a whole section passes then it is replaced with the value ``True``. If a
  439. whole section fails, then it is replaced with the value ``False``.
  440. If a value is missing, and there is no default in the check, then the check
  441. automatically fails.
  442. The ``validate`` method takes an optional keyword argument ``preserve_errors``.
  443. If you set this to ``True``, instead of getting ``False`` for failed checks you
  444. get the actual error object from the **validate** module. This usually contains
  445. useful information about why the check failed.
  446. See the `flatten_errors`_ function for how to turn your results dictionary into
  447. a useful list of error messages.
  448. Even if ``preserve_errors`` is ``True``, missing keys or sections will still be
  449. represented by a ``False`` in the results dictionary.
  450. Mentioning Default Values
  451. #########################
  452. In the check in your configspec, you can specify a default to be used - by
  453. using the ``default`` keyword. E.g. ::
  454. key1 = integer(0, 30, default=15)
  455. key2 = integer(default=15)
  456. key3 = boolean(default=True)
  457. key4 = option('Hello', 'Goodbye', 'Not Today', default='Not Today')
  458. If the configspec check supplies a default and the value is missing in the
  459. config, then the default will be set in your ConfigObj. (It is still passed to
  460. the ``Validator`` so that type conversion can be done: this means the default
  461. value must still pass the check.)
  462. ConfigObj keeps a record of which values come from defaults, using the
  463. ``defaults`` attribute of sections_. Any key in this list isn't written out by
  464. the ``write`` method. If a key is set from outside (even to the same value)
  465. then it is removed from the ``defaults`` list.
  466. .. note:
  467. Even if all the keys in a section are in the defaults list, the section
  468. marker is still written out.
  469. There is additionally a special case default value of ``None``. If you set the
  470. default value to ``None`` and the value is missing, the value will always be
  471. set to ``None``. As the other checks don't return ``None`` (unless you
  472. implement your own that do), you can tell that this value came from a default
  473. value (and was missing from the config file). It allows an easy way of
  474. implementing optional values. Simply check (and ignore) members that are set
  475. to ``None``.
  476. .. note::
  477. If stringify_ is ``False`` then ``default=None`` returns ``''`` instead of
  478. ``None``. This is because setting a value to a non-string raises an error
  479. if stringify is unset.
  480. The default value can be a list. See `List Values`_ for the way to do this.
  481. Writing invalid default values is a *guaranteed* way of confusing your users.
  482. Default values **must** pass the check.
  483. Mentioning Repeated Sections and Values
  484. #######################################
  485. In the configspec it is possible to cause *every* sub-section in a section to
  486. be validated using the same configspec. You do this with a section in the
  487. configspec called ``__many__``. Every sub-section in that section has the
  488. ``__many__`` configspec applied to it (without you having to explicitly name
  489. them in advance).
  490. Your ``__many__`` section can have nested subsections, which can also include
  491. ``__many__`` type sections.
  492. You can also specify that all values should be validated using the same configspec,
  493. by having a member with the name ``__many__``. If you want to use repeated values
  494. along with repeated sections then you can call one of them ``___many___`` (triple
  495. underscores).
  496. Sections with repeated sections or values can also have specifically named sub-sections
  497. or values. The ``__many__`` configspec will only be used to validate entries that don't
  498. have an explicit configspec.
  499. See `Repeated Sections`_ for examples.
  500. Mentioning SimpleVal
  501. ####################
  502. If you just want to check if all members are present, then you can use the
  503. ``SimpleVal`` object that comes with ConfigObj. It only fails members if they
  504. are missing.
  505. Write a configspec that has all the members you want to check for, but set
  506. every section to ``''``.
  507. .. code-block:: python
  508. val = SimpleVal()
  509. test = config.validate(val)
  510. if test is True:
  511. print 'Succeeded.'
  512. Mentioning copy Mode
  513. ####################
  514. As discussed in `Mentioning Default Values`_, you can use a configspec to
  515. supply default values. These are marked in the ConfigObj instance as defaults,
  516. and *not* written out by the ``write`` mode. This means that your users only
  517. need to supply values that are different from the defaults.
  518. This can be inconvenient if you *do* want to write out the default values,
  519. for example to write out a default config file.
  520. If you set ``copy=True`` when you call validate, then no values are marked as
  521. defaults. In addition, all comments from the configspec are copied into
  522. your ConfigObj instance. You can then call ``write`` to create your config
  523. file.
  524. There is a limitation with this. In order to allow `String Interpolation`_ to work
  525. within configspecs, ``DEFAULT`` sections are not processed by
  526. validation; even in copy mode.
  527. reload
  528. ~~~~~~
  529. If a ConfigObj instance was loaded from the filesystem, then this method will reload it. It
  530. will also reuse any configspec you supplied at instantiation (including reloading it from
  531. the filesystem if you passed it in as a filename).
  532. If the ConfigObj does not have a filename attribute pointing to a file, then a ``ReloadError``
  533. will be raised.
  534. reset
  535. ~~~~~
  536. This method takes no arguments and doesn't return anything. It restores a ConfigObj
  537. instance to a freshly created state.
  538. Attributes
  539. ----------
  540. A ConfigObj has the following attributes :
  541. * indent_type
  542. * interpolation
  543. * stringify
  544. * BOM
  545. * initial_comment
  546. * final_comment
  547. * list_values
  548. * encoding
  549. * default_encoding
  550. * unrepr
  551. * write_empty_values
  552. * newlines
  553. .. note::
  554. This doesn't include *comments*, *inline_comments*, *defaults*, or
  555. *configspec*. These are actually attributes of Sections_.
  556. It also has the following attributes as a result of parsing. They correspond to
  557. options when the ConfigObj was created, but changing them has no effect.
  558. * raise_errors
  559. * create_empty
  560. * file_error
  561. interpolation
  562. ~~~~~~~~~~~~~
  563. ConfigObj can perform string interpolation in a *similar* way to
  564. ``ConfigParser``. See the `String Interpolation`_ section for full details.
  565. If ``interpolation`` is set to ``False``, then interpolation is *not* done when
  566. you fetch values.
  567. stringify
  568. ~~~~~~~~~
  569. If this attribute is set (``True``) then the validate_ method changes the
  570. values in the ConfigObj. These are turned back into strings when write_ is
  571. called.
  572. If stringify is unset (``False``) then attempting to set a value to a non
  573. string (or a list of strings) will raise a ``TypeError``.
  574. BOM
  575. ~~~
  576. If the initial config file *started* with the UTF8 Unicode signature (known
  577. slightly incorrectly as the BOM - Byte Order Mark), or the UTF16 BOM, then
  578. this attribute is set to ``True``. Otherwise it is ``False``.
  579. If it is set to ``True`` when ``write`` is called then, if ``encoding`` is set
  580. to ``None`` *or* to ``utf_8`` (and variants) a UTF BOM will be written.
  581. For UTF16 encodings, a BOM is *always* written.
  582. initial_comment
  583. ~~~~~~~~~~~~~~~
  584. This is a list of lines. If the ConfigObj is created from an existing file, it
  585. will contain any lines of comments before the start of the members.
  586. If you create a new ConfigObj, this will be an empty list.
  587. The write method puts these lines before it starts writing out the members.
  588. final_comment
  589. ~~~~~~~~~~~~~
  590. This is a list of lines. If the ConfigObj is created from an existing file, it
  591. will contain any lines of comments after the last member.
  592. If you create a new ConfigObj, this will be an empty list.
  593. The ``write`` method puts these lines after it finishes writing out the
  594. members.
  595. list_values
  596. ~~~~~~~~~~~
  597. This attribute is ``True`` or ``False``. If set to ``False`` then values are
  598. not parsed for list values. In addition single line values are not unquoted.
  599. This allows you to do your own parsing of values. It exists primarily to
  600. support the reading of the configspec_ - but has other use cases.
  601. For example you could use the ``LineParser`` from the
  602. `listquote module <http://www.voidspace.org.uk/python/listquote.html#lineparser>`_
  603. to read values for nested lists.
  604. Single line values aren't quoted when writing - but multiline values are
  605. handled as normal.
  606. .. caution::
  607. Because values aren't quoted, leading or trailing whitespace can be lost. This behaviour was changed in version 4.0.1. Prior to this, single line values might have been quoted; even with ``list_values=False``. This means that files written by earlier versions of ConfigObj *could* now be incompatible and need the quotes removing by hand.
  608. encoding
  609. ~~~~~~~~
  610. This is the encoding used to encode the output, when you call ``write``. It
  611. must be a valid encoding `recognised by Python <http://docs.python.org/lib/standard-encodings.html>`_.
  612. If this value is ``None`` then no encoding is done when ``write`` is called.
  613. default_encoding
  614. ~~~~~~~~~~~~~~~~
  615. If encoding is set, any byte-strings in your ConfigObj instance (keys or
  616. members) will first be decoded to Unicode using the encoding specified by the
  617. ``default_encoding`` attribute. This ensures that the output is in the encoding
  618. specified.
  619. If this value is ``None`` then ``sys.defaultencoding`` is used instead.
  620. unrepr
  621. ~~~~~~
  622. Another boolean value. If this is set, then ``repr(value)`` is used to write
  623. values. This writes values in a slightly different way to the normal ConfigObj
  624. file syntax.
  625. This preserves basic Python data-types when read back in. See `unrepr mode`_
  626. for more details.
  627. write_empty_values
  628. ~~~~~~~~~~~~~~~~~~
  629. Also boolean. If set, values that are an empty string (``''``) are written as
  630. empty values. See `Empty Values`_ for more details.
  631. newlines
  632. ~~~~~~~~
  633. When a config file is read, ConfigObj records the type of newline separators in the
  634. file and uses this separator when writing. It defaults to ``None``, and ConfigObj
  635. uses the system default (``os.sep``) if write is called without newlines having
  636. been set.
  637. The Config File Format
  638. ======================
  639. You saw an example config file in the `Config Files`_ section. Here is a fuller
  640. specification of the config files used and created by ConfigObj.
  641. The basic pattern for keywords is::
  642. # comment line
  643. # comment line
  644. keyword = value # inline comment
  645. Both keyword and value can optionally be surrounded in quotes. The equals sign
  646. is the only valid divider.
  647. Values can have comments on the lines above them, and an inline comment after
  648. them. This, of course, is optional. See the comments_ section for details.
  649. If a keyword or value starts or ends with whitespace, or contains a quote mark
  650. or comma, then it should be surrounded by quotes. Quotes are not necessary if
  651. whitespace is surrounded by non-whitespace.
  652. Values can also be lists. Lists are comma separated. You indicate a single
  653. member list by a trailing comma. An empty list is shown by a single comma::
  654. keyword1 = value1, value2, value3
  655. keyword2 = value1, # a single member list
  656. keyword3 = , # an empty list
  657. Values that contain line breaks (multi-line values) can be surrounded by triple
  658. quotes. These can also be used if a value contains both types of quotes. List
  659. members cannot be surrounded by triple quotes::
  660. keyword1 = ''' A multi line value
  661. on several
  662. lines''' # with a comment
  663. keyword2 = '''I won't be "afraid".'''
  664. #
  665. keyword3 = """ A multi line value
  666. on several
  667. lines""" # with a comment
  668. keyword4 = """I won't be "afraid"."""
  669. .. warning::
  670. There is no way of safely quoting values that contain both types of triple
  671. quotes.
  672. A line that starts with a '#', possibly preceded by whitespace, is a comment.
  673. New sections are indicated by a section marker line. That is the section name
  674. in square brackets. Whitespace around the section name is ignored. The name can
  675. be quoted with single or double quotes. The marker can have comments before it
  676. and an inline comment after it::
  677. # The First Section
  678. [ section name 1 ] # first section
  679. keyword1 = value1
  680. # The Second Section
  681. [ "section name 2" ] # second section
  682. keyword2 = value2
  683. Any subsections (sections that are *inside* the current section) are
  684. designated by repeating the square brackets before and after the section name.
  685. The number of square brackets represents the nesting level of the sub-section.
  686. Square brackets may be separated by whitespace; such whitespace, however, will
  687. not be present in the output config written by the ``write`` method.
  688. Indentation is not significant, but can be preserved. See the description of
  689. the ``indent_type`` option, in the `ConfigObj specifications`_ chapter, for the
  690. details.
  691. A *NestingError* will be raised if the number of the opening and the closing
  692. brackets in a section marker is not the same, or if a sub-section's nesting
  693. level is greater than the nesting level of it parent plus one.
  694. In the outer section, single values can only appear before any sub-section.
  695. Otherwise they will belong to the sub-section immediately before them::
  696. # initial comment
  697. keyword1 = value1
  698. keyword2 = value2
  699. [section 1]
  700. keyword1 = value1
  701. keyword2 = value2
  702. [[sub-section]]
  703. # this is in section 1
  704. keyword1 = value1
  705. keyword2 = value2
  706. [[[nested section]]]
  707. # this is in sub section
  708. keyword1 = value1
  709. keyword2 = value2
  710. [[sub-section2]]
  711. # this is in section 1 again
  712. keyword1 = value1
  713. keyword2 = value2
  714. [[sub-section3]]
  715. # this is also in section 1, indentation is misleading here
  716. keyword1 = value1
  717. keyword2 = value2
  718. # final comment
  719. When parsed, the above config file produces the following data structure:
  720. .. code-block:: python
  721. ConfigObj({
  722. 'keyword1': 'value1',
  723. 'keyword2': 'value2',
  724. 'section 1': {
  725. 'keyword1': 'value1',
  726. 'keyword2': 'value2',
  727. 'sub-section': {
  728. 'keyword1': 'value1',
  729. 'keyword2': 'value2',
  730. 'nested section': {
  731. 'keyword1': 'value1',
  732. 'keyword2': 'value2',
  733. },
  734. },
  735. 'sub-section2': {
  736. 'keyword1': 'value1',
  737. 'keyword2': 'value2',
  738. },
  739. 'sub-section3': {
  740. 'keyword1': 'value1',
  741. 'keyword2': 'value2',
  742. },
  743. },
  744. })
  745. Sections are ordered: note how the structure of the resulting ConfigObj is in
  746. the same order as the original file.
  747. .. note::
  748. In ConfigObj 4.3.0 *empty values* became valid syntax. They are read as the
  749. empty string. There is also an option/attribute (``write_empty_values``) to
  750. allow the writing of these.
  751. This is mainly to support 'legacy' config files, written from other
  752. applications. This is documented under `Empty Values`_.
  753. `unrepr mode`_ introduces *another* syntax variation, used for storing
  754. basic Python datatypes in config files.
  755. Sections
  756. ========
  757. Every section in a ConfigObj has certain properties. The ConfigObj itself also
  758. has these properties, because it too is a section (sometimes called the *root
  759. section*).
  760. ``Section`` is a subclass of the standard new-class dictionary, therefore it
  761. has **all** the methods of a normal dictionary. This means you can ``update``
  762. and ``clear`` sections.
  763. .. note::
  764. You create a new section by assigning a member to be a dictionary.
  765. The new ``Section`` is created *from* the dictionary, but isn't the same
  766. thing as the dictionary. (So references to the dictionary you use to create
  767. the section *aren't* references to the new section).
  768. Note the following.
  769. .. code-block:: python
  770. config = ConfigObj()
  771. vals = {'key1': 'value 1',
  772. 'key2': 'value 2'
  773. }
  774. config['vals'] = vals
  775. config['vals'] == vals
  776. True
  777. config['vals'] is vals
  778. False
  779. If you now change ``vals``, the changes won't be reflected in ``config['vals']``.
  780. A section is ordered, following its ``scalars`` and ``sections``
  781. attributes documented below. This means that the following dictionary
  782. attributes return their results in order.
  783. * '__iter__'
  784. More commonly known as ``for member in section:``.
  785. * '__repr__' and '__str__'
  786. Any time you print or display the ConfigObj.
  787. * 'items'
  788. * 'iteritems'
  789. * 'iterkeys'
  790. * 'itervalues'
  791. * 'keys'
  792. * 'popitem'
  793. * 'values'
  794. Section Attributes
  795. ------------------
  796. * main
  797. A reference to the main ConfigObj.
  798. * parent
  799. A reference to the 'parent' section, the section that this section is a
  800. member of.
  801. On the ConfigObj this attribute is a reference to itself. You can use this
  802. to walk up the sections, stopping when ``section.parent is section``.
  803. * depth
  804. The nesting level of the current section.
  805. If you create a new ConfigObj and add sections, 1 will be added to the
  806. depth level between sections.
  807. * defaults
  808. This attribute is a list of scalars that came from default values. Values
  809. that came from defaults aren't written out by the ``write`` method.
  810. Setting any of these values in the section removes them from the defaults
  811. list.
  812. * default_values
  813. This attribute is a dictionary mapping keys to the default values for the
  814. keys. By default it is an empty dictionary and is populated when you
  815. validate the ConfigObj.
  816. * scalars, sections
  817. These attributes are normal lists, representing the order that members,
  818. single values and subsections appear in the section. The order will either
  819. be the order of the original config file, *or* the order that you added
  820. members.
  821. The order of members in this lists is the order that ``write`` creates in
  822. the config file. The ``scalars`` list is output before the ``sections``
  823. list.
  824. Adding or removing members also alters these lists. You can manipulate the
  825. lists directly to alter the order of members.
  826. .. warning::
  827. If you alter the ``scalars``, ``sections``, or ``defaults`` attributes
  828. so that they no longer reflect the contents of the section, you will
  829. break your ConfigObj.
  830. See also the ``rename`` method.
  831. * comments
  832. This is a dictionary of comments associated with each member. Each entry is
  833. a list of lines. These lines are written out before the member.
  834. * inline_comments
  835. This is *another* dictionary of comments associated with each member. Each
  836. entry is a string that is put inline with the member.
  837. * configspec
  838. The configspec attribute is a dictionary mapping scalars to *checks*. A
  839. check defines the expected type and possibly the allowed values for a
  840. member.
  841. The configspec has the same format as a config file, but instead of values
  842. it has a specification for the value (which may include a default value).
  843. The validate_ method uses it to check the config file makes sense. If a
  844. configspec is passed in when the ConfigObj is created, then it is parsed
  845. and broken up to become the ``configspec`` attribute of each section.
  846. If you didn't pass in a configspec, this attribute will be ``None`` on the
  847. root section (the main ConfigObj).
  848. You can set the configspec attribute directly on a section.
  849. See the validation_ section for full details of how to write configspecs.
  850. * extra_values
  851. By default an empty list. After validation_ this is populated with any members
  852. of the section that don't appear in the configspec (i.e. they are additional
  853. values). Rather than accessing this directly it may be more convenient to get
  854. all the extra values in a config file using the get_extra_values_ function.
  855. New in ConfigObj 4.7.0.
  856. Section Methods
  857. ---------------
  858. * **dict**
  859. This method takes no arguments. It returns a deep copy of the section as a
  860. dictionary. All subsections will also be dictionaries, and list values will
  861. be copies, rather than references to the original [#]_.
  862. * **rename**
  863. ``rename(oldkey, newkey)``
  864. This method renames a key, without affecting its position in the sequence.
  865. * **merge**
  866. ``merge(indict)``
  867. This method is a *recursive update* method. It allows you to merge two
  868. config files together.
  869. You would typically use this to create a default ConfigObj and then merge
  870. in user settings. This way users only need to specify values that are
  871. different from the default.
  872. For example :
  873. .. code-block:: python
  874. # def_cfg contains your default config settings
  875. # user_cfg contains the user settings
  876. cfg = ConfigObj(def_cfg)
  877. usr = ConfigObj(user_cfg)
  878. #
  879. cfg.merge(usr)
  880. """
  881. cfg now contains a combination of the default settings and the user
  882. settings.
  883. The user settings will have overwritten any of the default ones.
  884. """
  885. * **walk**
  886. This method can be used to transform values and names. See `walking a
  887. section`_ for examples and explanation.
  888. * **as_bool**
  889. ``as_bool(key)``
  890. Returns ``True`` if the key contains a string that represents ``True``, or
  891. is the ``True`` object.
  892. Returns ``False`` if the key contains a string that represents ``False``,
  893. or is the ``False`` object.
  894. Raises a ``ValueError`` if the key contains anything else.
  895. Strings that represent ``True`` are (not case sensitive)::
  896. true, yes, on, 1
  897. Strings that represent ``False`` are::
  898. false, no, off, 0
  899. * **as_int**
  900. ``as_int(key)``
  901. This returns the value contained in the specified key as an integer.
  902. It raises a ``ValueError`` if the conversion can't be done.
  903. * **as_float**
  904. ``as_float(key)``
  905. This returns the value contained in the specified key as a float.
  906. It raises a ``ValueError`` if the conversion can't be done.
  907. * **as_list**
  908. ``as_list(key)``
  909. This returns the value contained in the specified key as a list.
  910. If it isn't a list it will be wrapped as a list so that you can
  911. guarantee the returned value will be a list.
  912. * **restore_default**
  913. ``restore_default(key)``
  914. Restore (and return) the default value for the specified key.
  915. This method will only work for a ConfigObj that was created
  916. with a configspec and has been validated.
  917. If there is no default value for this key, ``KeyError`` is raised.
  918. * **restore_defaults**
  919. ``restore_defaults()``
  920. Recursively restore default values to all members
  921. that have them.
  922. This method will only work for a ConfigObj that was created
  923. with a configspec and has been validated.
  924. It doesn't delete or modify entries without default values.
  925. Walking a Section
  926. -----------------
  927. .. note::
  928. The walk method allows you to call a function on every member/name.
  929. .. code-block:: python
  930. walk(function, raise_errors=True,
  931. call_on_sections=False, **keywargs)
  932. ``walk`` is a method of the ``Section`` object. This means it is also a method
  933. of ConfigObj.
  934. It walks through every member and calls a function on the keyword and value. It
  935. walks recursively through subsections.
  936. It returns a dictionary of all the computed values.
  937. If the function raises an exception, the default is to propagate the error, and
  938. stop. If ``raise_errors=False`` then it sets the return value for that keyword
  939. to ``False`` instead, and continues. This is similar to the way validation_
  940. works.
  941. Your function receives the arguments ``(section, key)``. The current value is
  942. then ``section[key]`` [#]_. Any unrecognised keyword arguments you pass to
  943. walk, are passed on to the function.
  944. Normally ``walk`` just recurses into subsections. If you are transforming (or
  945. checking) names as well as values, then you want to be able to change the names
  946. of sections. In this case set ``call_on_sections`` to ``True``. Now, on
  947. encountering a sub-section, *first* the function is called for the *whole*
  948. sub-section, and *then* it recurses into it's members. This means your function
  949. must be able to handle receiving dictionaries as well as strings and lists.
  950. If you are using the return value from ``walk`` *and* ``call_on_sections``,
  951. note that walk discards the return value when it calls your function.
  952. .. caution::
  953. You can use ``walk`` to transform the names of members of a section
  954. but you mustn't add or delete members.
  955. Examples
  956. --------
  957. You can use this for transforming all values in your ConfigObj. For example
  958. you might like the nested lists from ConfigObj 3. This was provided by the
  959. listquote_ module. You could switch off the parsing for list values
  960. (``list_values=False``) and use listquote to parse every value.
  961. Another thing you might want to do is use the Python escape codes in your
  962. values. You might be *used* to using ``\n`` for line feed and ``\t`` for tab.
  963. Obviously we'd need to decode strings that come from the config file (using the
  964. escape codes). Before writing out we'll need to put the escape codes back in
  965. encode.
  966. As an example we'll write a function to use with walk, that encodes or decodes
  967. values using the ``string-escape`` codec.
  968. The function has to take each value and set the new value. As a bonus we'll
  969. create one function that will do decode *or* encode depending on a keyword
  970. argument.
  971. We don't want to work with section names, we're only transforming values, so
  972. we can leave ``call_on_sections`` as ``False``. This means the two datatypes we
  973. have to handle are strings and lists, we can ignore everything else. (We'll
  974. treat tuples as lists as well).
  975. We're not using the return values, so it doesn't need to return anything, just
  976. change the values if appropriate.
  977. .. code-block:: python
  978. def string_escape(section, key, encode=False):
  979. """
  980. A function to encode or decode using the 'string-escape' codec.
  981. To be passed to the walk method of a ConfigObj.
  982. By default it decodes.
  983. To encode, pass in the keyword argument ``encode=True``.
  984. """
  985. val = section[key]
  986. # is it a type we can work with
  987. # NOTE: for platforms where Python > 2.2
  988. # you can use basestring instead of (str, unicode)
  989. if not isinstance(val, (str, unicode, list, tuple)):
  990. # no !
  991. return
  992. elif isinstance(val, (str, unicode)):
  993. # it's a string !
  994. if not encode:
  995. section[key] = val.decode('string-escape')
  996. else:
  997. section[key] = val.encode('string-escape')
  998. else:
  999. # it must be a list or tuple!
  1000. # we'll be lazy and create a new list
  1001. newval = []
  1002. # we'll check every member of the list
  1003. for entry in val:
  1004. if isinstance(entry, (str, unicode)):
  1005. if not encode:
  1006. newval.append(entry.decode('string-escape'))
  1007. else:
  1008. newval.append(entry.encode('string-escape'))
  1009. else:
  1010. newval.append(entry)
  1011. # done !
  1012. section[key] = newval
  1013. # assume we have a ConfigObj called ``config``
  1014. #
  1015. # To decode
  1016. config.walk(string_escape)
  1017. #
  1018. # To encode.
  1019. # Because ``walk`` doesn't recognise the ``encode`` argument
  1020. # it passes it to our function.
  1021. config.walk(string_escape, encode=True)
  1022. Here's a simple example of using ``walk`` to transform names and values. One
  1023. usecase of this would be to create a *standard* config file with placeholders
  1024. for section and keynames. You can then use walk to create new config files
  1025. and change values and member names :
  1026. .. code-block:: python
  1027. # We use 'XXXX' as a placeholder
  1028. config = '''
  1029. XXXXkey1 = XXXXvalue1
  1030. XXXXkey2 = XXXXvalue2
  1031. XXXXkey3 = XXXXvalue3
  1032. [XXXXsection1]
  1033. XXXXkey1 = XXXXvalue1
  1034. XXXXkey2 = XXXXvalue2
  1035. XXXXkey3 = XXXXvalue3
  1036. [XXXXsection2]
  1037. XXXXkey1 = XXXXvalue1
  1038. XXXXkey2 = XXXXvalue2
  1039. XXXXkey3 = XXXXvalue3
  1040. [[XXXXsection1]]
  1041. XXXXkey1 = XXXXvalue1
  1042. XXXXkey2 = XXXXvalue2
  1043. XXXXkey3 = XXXXvalue3
  1044. '''.splitlines()
  1045. cfg = ConfigObj(config)
  1046. #
  1047. def transform(section, key):
  1048. val = section[key]
  1049. newkey = key.replace('XXXX', 'CLIENT1')
  1050. section.rename(key, newkey)
  1051. if isinstance(val, (tuple, list, dict)):
  1052. pass
  1053. else:
  1054. val = val.replace('XXXX', 'CLIENT1')
  1055. section[newkey] = val
  1056. #
  1057. cfg.walk(transform, call_on_sections=True)
  1058. print cfg
  1059. ConfigObj({'CLIENT1key1': 'CLIENT1value1', 'CLIENT1key2': 'CLIENT1value2',
  1060. 'CLIENT1key3': 'CLIENT1value3',
  1061. 'CLIENT1section1': {'CLIENT1key1': 'CLIENT1value1',
  1062. 'CLIENT1key2': 'CLIENT1value2', 'CLIENT1key3': 'CLIENT1value3'},
  1063. 'CLIENT1section2': {'CLIENT1key1': 'CLIENT1value1',
  1064. 'CLIENT1key2': 'CLIENT1value2', 'CLIENT1key3': 'CLIENT1value3',
  1065. 'CLIENT1section1': {'CLIENT1key1': 'CLIENT1value1',
  1066. 'CLIENT1key2': 'CLIENT1value2', 'CLIENT1key3': 'CLIENT1value3'}}})
  1067. Exceptions
  1068. ==========
  1069. There are several places where ConfigObj may raise exceptions (other than
  1070. because of bugs).
  1071. 1) If a configspec filename you pass in doesn't exist, or a config file
  1072. filename doesn't exist *and* ``file_error=True``, an ``IOError`` will be
  1073. raised.
  1074. 2) If you try to set a non-string key, or a non string value when
  1075. ``stringify=False``, a ``TypeError`` will be raised.
  1076. 3) A badly built config file will cause parsing errors.
  1077. 4) A parsing error can also occur when reading a configspec.
  1078. 5) In string interpolation you can specify a value that doesn't exist, or
  1079. create circular references (recursion).
  1080. Number 5 (which is actually two different types of exceptions) is documented
  1081. in `String Interpolation`_.
  1082. *This* section is about errors raised during parsing.
  1083. The base error class is ``ConfigObjError``. This is a subclass of
  1084. ``SyntaxError``, so you can trap for ``SyntaxError`` without needing to
  1085. directly import any of the ConfigObj exceptions.
  1086. The following other exceptions are defined (all deriving from
  1087. ``ConfigObjError``) :
  1088. * ``NestingError``
  1089. This error indicates either a mismatch in the brackets in a section marker,
  1090. or an excessive level of nesting.
  1091. * ``ParseError``
  1092. This error indicates that a line is badly written. It is neither a valid
  1093. ``key = value`` line, nor a valid section marker line, nor a comment line.
  1094. * ``DuplicateError``
  1095. The keyword or section specified already exists.
  1096. * ``ConfigspecError``
  1097. An error occurred whilst parsing a configspec.
  1098. * ``UnreprError``
  1099. An error occurred when parsing a value in `unrepr mode`_.
  1100. * ``ReloadError``
  1101. ``reload`` was called on a ConfigObj instance that doesn't have a valid
  1102. filename attribute.
  1103. When parsing a configspec, ConfigObj will stop on the first error it
  1104. encounters. It will raise a ``ConfigspecError``. This will have an ``error``
  1105. attribute, which is the actual error that was raised.
  1106. Behaviour when parsing a config file depends on the option ``raise_errors``.
  1107. If ConfigObj encounters an error while parsing a config file:
  1108. If ``raise_errors=True`` then ConfigObj will raise the appropriate error
  1109. and parsing will stop.
  1110. If ``raise_errors=False`` (the default) then parsing will continue to the
  1111. end and *all* errors will be collected.
  1112. If ``raise_errors`` is False and multiple errors are found a ``ConfigObjError``
  1113. is raised. The error raised has a ``config`` attribute, which is the parts of
  1114. the ConfigObj that parsed successfully. It also has an attribute ``errors``,
  1115. which is a list of *all* the errors raised. Each entry in the list is an
  1116. instance of the appropriate error type. Each one has the following attributes
  1117. (useful for delivering a sensible error message to your user) :
  1118. * ``line``: the original line that caused the error.
  1119. * ``line_number``: its number in the config file.
  1120. * ``message``: the error message that accompanied the error.
  1121. If only one error is found, then that error is re-raised. The error still has
  1122. the ``config`` and ``errors`` attributes. This means that your error handling
  1123. code can be the same whether one error is raised in parsing , or several.
  1124. It also means that in the most common case (a single error) a useful error
  1125. message will be raised.
  1126. .. note::
  1127. One wrongly written line could break the basic structure of your config
  1128. file. This could cause every line after it to flag an error, so having a
  1129. list of all the lines that caused errors may not be as useful as it sounds.
  1130. Validation
  1131. ==========
  1132. .. hint::
  1133. The system of configspecs can seem confusing at first, but is actually
  1134. quite simple and powerful. The best reference is my article on ConfigObj:
  1135. * `An Introduction to ConfigObj`_
  1136. Validation is done through a combination of the configspec_ and a ``Validator``
  1137. object. For this you need *validate.py* [#]_. See downloading_ if you don't
  1138. have a copy.
  1139. Validation can perform two different operations :
  1140. 1) Check that a value meets a specification. For example, check that a value
  1141. is an integer between one and six, or is a choice from a specific set of
  1142. options.
  1143. 2) It can convert the value into the type required. For example, if one of
  1144. your values is a port number, validation will turn it into an integer for
  1145. you.
  1146. So validation can act as a transparent layer between the datatypes of your
  1147. application configuration (boolean, integers, floats, etc) and the text format
  1148. of your config file.
  1149. configspec
  1150. ----------
  1151. The ``validate`` method checks members against an entry in the configspec. Your
  1152. configspec therefore resembles your config file, with a check for every member.
  1153. In order to perform validation you need a ``Validator`` object. This has
  1154. several useful built-in check functions. You can also create your own custom
  1155. functions and register them with your Validator object.
  1156. Each check is the name of one of these functions, including any parameters and
  1157. keyword arguments. The configspecs look like function calls, and they map to
  1158. function calls.
  1159. The basic datatypes that an un-extended Validator can test for are :
  1160. * boolean values (True and False)
  1161. * integers (including minimum and maximum values)
  1162. * floats (including min and max)
  1163. * strings (including min and max length)
  1164. * IP addresses (v4 only)
  1165. It can also handle lists of these types and restrict a value to being one from
  1166. a set of options.
  1167. An example configspec is going to look something like::
  1168. port = integer(0, 100)
  1169. user = string(max=25)
  1170. mode = option('quiet', 'loud', 'silent')
  1171. You can specify default values, and also have the same configspec applied to
  1172. several sections. This is called `repeated sections`_.
  1173. For full details on writing configspecs, please refer to the `validate.py
  1174. documentation`_.
  1175. .. important::
  1176. Your configspec is read by ConfigObj in the same way as a config file.
  1177. That means you can do interpolation *within* your configspec.
  1178. In order to allow this, checks in the 'DEFAULT' section (of the root level
  1179. of your configspec) are *not* used.
  1180. If you want to use a configspec *without* interpolation being done in it
  1181. you can create your configspec manually and switch off interpolation:
  1182. .. code-block:: python
  1183. from configobj import ConfigObj
  1184. configspec = ConfigObj(spec_filename, interpolation=False, list_values=False,
  1185. _inspec=True)
  1186. conf = ConfigObj(config_filename, configspec=configspec)
  1187. If you need to specify the encoding of your configspec, then you can pass in a
  1188. ConfigObj instance as your configspec. When you read your configspec file, you
  1189. *must* specify ``list_values=False``. If you need to support hashes in
  1190. configspec values then you must also pass in ``_inspec=True``.
  1191. .. code-block:: python
  1192. from configobj import ConfigObj
  1193. configspec = ConfigObj(configspecfilename, encoding='UTF8',
  1194. list_values=False, _inspec=True)
  1195. config = ConfigObj(filename, configspec=configspec)
  1196. .. _validate.py documentation: http://www.voidspace.org.uk/python/validate.html
  1197. Type Conversion
  1198. ---------------
  1199. By default, validation does type conversion. This means that if you specify
  1200. ``integer`` as the check, then calling validate_ will actually change the value
  1201. to an integer (so long as the check succeeds).
  1202. It also means that when you call the write_ method, the value will be converted
  1203. back into a string using the ``str`` function.
  1204. To switch this off, and leave values as strings after validation, you need to
  1205. set the stringify_ attribute to ``False``. If this is the case, attempting to
  1206. set a value to a non-string will raise an error.
  1207. Default Values
  1208. --------------
  1209. You can set a default value in your check. If the value is missing from the
  1210. config file then this value will be used instead. This means that your user
  1211. only has to supply values that differ from the defaults.
  1212. If you *don't* supply a default then for a value to be missing is an error,
  1213. and this will show in the `return value`_ from validate.
  1214. Additionally you can set the default to be ``None``. This means the value will
  1215. be set to ``None`` (the object) *whichever check is used*. (It will be set to
  1216. ``''`` rather than ``None`` if stringify_ is ``False``). You can use this
  1217. to easily implement optional values in your config files. ::
  1218. port = integer(0, 100, default=80)
  1219. user = string(max=25, default=0)
  1220. mode = option('quiet', 'loud', 'silent', default='loud')
  1221. nick = string(default=None)
  1222. .. note::
  1223. Because the default goes through type conversion, it also has to pass the
  1224. check.
  1225. Note that ``default=None`` is case sensitive.
  1226. List Values
  1227. ~~~~~~~~~~~
  1228. It's possible that you will want to specify a list as a default value. To avoid
  1229. confusing syntax with commas and quotes you use a list constructor to specify
  1230. that keyword arguments are lists. This includes the ``default`` value. This
  1231. makes checks look something like::
  1232. checkname(default=list('val1', 'val2', 'val3'))
  1233. This works with all keyword arguments, but is most useful for default values.
  1234. Repeated Sections
  1235. -----------------
  1236. Repeated sections are a way of specifying a configspec for a section that
  1237. should be applied to all unspecified subsections in the same section.
  1238. The easiest way of explaining this is to give an example. Suppose you have a
  1239. config file that describes a dog. That dog has various attributes, but it can
  1240. also have many fleas. You don't know in advance how many fleas there will be,
  1241. or what they will be called, but you want each flea validated against the same
  1242. configspec.
  1243. We can define a section called *fleas*. We want every flea in that section
  1244. (every sub-section) to have the same configspec applied to it. We do this by
  1245. defining a single section called ``__many__``. ::
  1246. [dog]
  1247. name = string(default=Rover)
  1248. age = float(0, 99, default=0)
  1249. [[fleas]]
  1250. [[[__many__]]]
  1251. bloodsucker = boolean(default=True)
  1252. children = integer(default=10000)
  1253. size = option(small, tiny, micro, default=tiny)
  1254. Every flea on our dog will now be validated using the ``__many__`` configspec.
  1255. ``__many__`` sections can have sub-sections, including their own ``__many__``
  1256. sub-sections. Defaults work in the normal way in repeated sections.
  1257. Repeated Values
  1258. ---------------
  1259. As well as using ``__many__`` to validate unspecified sections you can use it to validate values. For
  1260. example, to specify that all values in a section should be integers::
  1261. [section]
  1262. __many__ = integer
  1263. If you want to use repeated values alongside repeated sections you can call one ``__many__`` and the
  1264. other ``___many___`` (with three underscores).
  1265. Copy Mode
  1266. ---------
  1267. Because you can specify default values in your configspec, you can use
  1268. ConfigObj to write out default config files for your application.
  1269. However, normally values supplied from a default in a configspec are *not*
  1270. written out by the ``write`` method.
  1271. To do this, you need to specify ``copy=True`` when you call validate. As well
  1272. as not marking values as default, all the comments in the configspec file
  1273. will be copied into your ConfigObj instance.
  1274. .. code-block:: python
  1275. from configobj import ConfigObj
  1276. from validate import Validator
  1277. vdt = Validator()
  1278. config = ConfigObj(configspec='default.ini')
  1279. config.filename = 'new_default.ini'
  1280. config.validate(vdt, copy=True)
  1281. config.write()
  1282. If you need to support hashes in the configspec values then you must create
  1283. it with ``_inspec=True``. This has the side effect of switching off the parsing
  1284. of inline comments, meaning that they won't be copied into the new config file.
  1285. (ConfigObj syntax is slightly different from configspec syntax and the parser
  1286. can't support both inline comments and hashes in configspec values.)
  1287. Validation and Interpolation
  1288. ----------------------------
  1289. String interpolation and validation don't play well together. When validation
  1290. changes type it sets the value. If the value uses interpolation, then the
  1291. interpolation reference would normally be overwritten. Calling ``write`` would
  1292. then use the absolute value and the interpolation reference would be lost.
  1293. As a compromise - if the value is unchanged by validation then it is not reset.
  1294. This means strings that pass through validation unmodified will not be
  1295. overwritten. If validation changes type - the value has to be overwritten, and
  1296. any interpolation references are lost.
  1297. Extra Values
  1298. ------------
  1299. After validation the ``extra_values`` member of every section that is listed in
  1300. the configspec will be populated with the names of members that are in the
  1301. config file but not in the configspec.
  1302. If you are reporting configuration errors to your user this information can be
  1303. useful, for example some missing entries may be due to misspelt entries that
  1304. appear as extra values.
  1305. See the get_extra_values_ function
  1306. New in ConfigObj 4.7.0.
  1307. SimpleVal
  1308. ---------
  1309. You may not need a full validation process, but still want to check if all the
  1310. expected values are present.
  1311. Provided as part of the ConfigObj module is the ``SimpleVal`` object. This has
  1312. a dummy ``test`` method that always passes.
  1313. The only reason a test will fail is if the value is missing. The return value
  1314. from ``validate`` will either be ``True``, meaning all present, or a dictionary
  1315. with ``False`` for all missing values/sections.
  1316. To use it, you still need to pass in a valid configspec when you create the
  1317. ConfigObj, but just set all the values to ``''``. Then create an instance of
  1318. ``SimpleVal`` and pass it to the ``validate`` method.
  1319. As a trivial example if you had the following config file::
  1320. # config file for an application
  1321. port = 80
  1322. protocol = http
  1323. domain = voidspace
  1324. top_level_domain = org.uk
  1325. You would write the following configspec::
  1326. port = ''
  1327. protocol = ''
  1328. domain = ''
  1329. top_level_domain = ''
  1330. .. code-block:: python
  1331. config = Configobj(filename, configspec=configspec)
  1332. val = SimpleVal()
  1333. test = config.validate(val)
  1334. if test == True:
  1335. print 'All values present.'
  1336. elif test == False:
  1337. print 'No values present!'
  1338. else:
  1339. for entry in test:
  1340. if test[entry] == False:
  1341. print '"%s" missing.' % entry
  1342. Empty values
  1343. ============
  1344. Many config files from other applications allow empty values. As of version
  1345. 4.3.0, ConfigObj will read these as an empty string.
  1346. A new option/attribute has been added (``write_empty_values``) to allow
  1347. ConfigObj to write empty strings as empty values.
  1348. .. code-block:: python
  1349. from configobj import ConfigObj
  1350. cfg = '''
  1351. key =
  1352. key2 = # a comment
  1353. '''.splitlines()
  1354. config = ConfigObj(cfg)
  1355. print config
  1356. ConfigObj({'key': '', 'key2': ''})
  1357. config.write_empty_values = True
  1358. for line in config.write():
  1359. print line
  1360. key =
  1361. key2 = # a comment
  1362. unrepr mode
  1363. ===========
  1364. The ``unrepr`` option allows you to store and retrieve the basic Python
  1365. data-types using config files. It has to use a slightly different syntax to
  1366. normal ConfigObj files. Unsurprisingly it uses Python syntax.
  1367. This means that lists are different (they are surrounded by square brackets),
  1368. and strings *must* be quoted.
  1369. The types that ``unrepr`` can work with are :
  1370. | strings, lists tuples
  1371. | None, True, False
  1372. | dictionaries, integers, floats
  1373. | longs and complex numbers
  1374. You can't store classes, types or instances.
  1375. ``unrepr`` uses ``repr(object)`` to write out values, so it currently *doesn't*
  1376. check that you are writing valid objects. If you attempt to read an unsupported
  1377. value, ConfigObj will raise a ``configobj.UnknownType`` exception.
  1378. Values that are triple quoted cased. The triple quotes are removed *before*
  1379. converting. This means that you can use triple quotes to write dictionaries
  1380. over several lines in your config files. They won't be written like this
  1381. though.
  1382. If you are writing config files by hand, for use with ``unrepr``, you should
  1383. be aware of the following differences from normal ConfigObj syntax :
  1384. | List : ``['A List', 'With', 'Strings']``
  1385. | Strings : ``"Must be quoted."``
  1386. | Backslash : ``"The backslash must be escaped \\"``
  1387. These all follow normal Python syntax.
  1388. In unrepr mode *inline comments* are not saved. This is because lines are
  1389. parsed using the `compiler package <http://docs.python.org/lib/compiler.html>`_
  1390. which discards comments.
  1391. String Interpolation
  1392. ====================
  1393. .. note::
  1394. String interpolation can slow down (slightly) the fetching of values
  1395. from your config object. If you aren't using interpolation and it
  1396. is performance critical then create your instance with
  1397. ``interpolation=False``.
  1398. ConfigObj allows string interpolation *similar* to the way ``ConfigParser``
  1399. or ``string.Template`` work. The value of the ``interpolation`` attribute
  1400. determines which style of interpolation you want to use. Valid values are
  1401. "ConfigParser" or "Template" (case-insensitive, so "configparser" and
  1402. "template" will also work). For backwards compatibility reasons, the value
  1403. ``True`` is also a valid value for the ``interpolation`` attribute, and
  1404. will select ``ConfigParser``-style interpolation. At some undetermined point
  1405. in the future, that default *may* change to ``Template``-style interpolation.
  1406. For ``ConfigParser``-style interpolation, you specify a value to be
  1407. substituted by including ``%(name)s`` in the value.
  1408. For ``Template``-style interpolation, you specify a value to be substituted
  1409. by including ``${cl}name{cr}`` in the value. Alternately, if 'name' is a valid
  1410. Python identifier (i.e., is composed of nothing but alphanumeric characters,
  1411. plus the underscore character), then the braces are optional and the value
  1412. can be written as ``$name``.
  1413. Note that ``ConfigParser``-style interpolation and ``Template``-style
  1414. interpolation are mutually exclusive; you cannot have a configuration file
  1415. that's a mix of one or the other. Pick one and stick to it. ``Template``-style
  1416. interpolation is simpler to read and write by hand, and is recommended if
  1417. you don't have a particular reason to use ``ConfigParser``-style.
  1418. Interpolation checks first the current section to see if ``name`` is the key
  1419. to a value. ('name' is case sensitive).
  1420. If it doesn't find it, next it checks the 'DEFAULT' sub-section of the current
  1421. section.
  1422. If it still doesn't find it, it moves on to check the parent section and the
  1423. parent section's 'DEFAULT' subsection, and so on all the way up to the main
  1424. section.
  1425. If the value specified isn't found in any of these locations, then a
  1426. ``MissingInterpolationOption`` error is raised (a subclass of
  1427. ``ConfigObjError``).
  1428. If it is found then the returned value is also checked for substitutions. This
  1429. allows you to make up compound values (for example directory paths) that use
  1430. more than one default value. It also means it's possible to create circular
  1431. references. If there are any circular references which would cause an infinite
  1432. interpolation loop, an ``InterpolationLoopError`` is raised.
  1433. Both of these errors are subclasses of ``InterpolationError``, which is a
  1434. subclass of ``ConfigObjError``.
  1435. String interpolation and validation don't play well together. This is because
  1436. validation overwrites values - and so may erase the interpolation references.
  1437. See `Validation and Interpolation`_. (This can only happen if validation
  1438. has to *change* the value).
  1439. New in ConfigObj 4.7.0: String interpolation is now done in members of list
  1440. values.
  1441. String Interpolation and List Values
  1442. ------------------------------------
  1443. Since version 4.7 string interpolation is done on string members of list values.
  1444. If interpolation changes any members of the list then what you get back is a
  1445. *copy* of the list rather than the original list.
  1446. This makes fetching list values slightly slower when interpolation is on, it
  1447. also means that if you mutate the list changes won't be reflected in the
  1448. original list:
  1449. .. code-block:: python
  1450. >>> c = ConfigObj()
  1451. >>> c['foo'] = 'boo'
  1452. >>> c['bar'] = ['%(foo)s']
  1453. >>> c['bar']
  1454. ['boo']
  1455. >>> c['bar'].append('fish')
  1456. >>> c['bar']
  1457. ['boo']
  1458. Instead of mutating the list you must create a new list and reassign it.
  1459. Comments
  1460. ========
  1461. Any line that starts with a '#', possibly preceded by whitespace, is a comment.
  1462. If a config file starts with comments then these are preserved as the
  1463. initial_comment_.
  1464. If a config file ends with comments then these are preserved as the
  1465. final_comment_.
  1466. Every key or section marker may have lines of comments immediately above it.
  1467. These are saved as the ``comments`` attribute of the section. Each member is a
  1468. list of lines.
  1469. You can also have a comment inline with a value. These are saved as the
  1470. ``inline_comments`` attribute of the section, with one entry per member of the
  1471. section.
  1472. Subsections (section markers in the config file) can also have comments.
  1473. See `Section Attributes`_ for more on these attributes.
  1474. These comments are all written back out by the ``write`` method.
  1475. flatten_errors
  1476. ==============
  1477. .. code-block:: python
  1478. flatten_errors(cfg, res)
  1479. Validation_ is a powerful way of checking that the values supplied by the user
  1480. make sense.
  1481. The validate_ method returns a results dictionary that represents pass or fail
  1482. for each value. This doesn't give you any information about *why* the check
  1483. failed.
  1484. ``flatten_errors`` is an example function that turns a results dictionary into
  1485. a flat list, that only contains values that *failed*.
  1486. ``cfg`` is the ConfigObj instance being checked, ``res`` is the results
  1487. dictionary returned by ``validate``.
  1488. It returns a list of keys that failed. Each member of the list is a tuple::
  1489. ([list of sections...], key, result)
  1490. If ``validate`` was called with ``preserve_errors=False`` (the default)
  1491. then ``result`` will always be ``False``.
  1492. *list of sections* is a flattened list of sections that the key was found
  1493. in.
  1494. If the section was missing then key will be ``None``.
  1495. If the value (or section) was missing then ``result`` will be ``False``.
  1496. If ``validate`` was called with ``preserve_errors=True`` and a value
  1497. was present, but failed the check, then ``result`` will be the exception
  1498. object returned. You can use this as a string that describes the failure.
  1499. For example :
  1500. *The value "3" is of the wrong type*.
  1501. Example Usage
  1502. -------------
  1503. The output from ``flatten_errors`` is a list of tuples.
  1504. Here is an example of how you could present this information to the user.
  1505. .. code-block:: python
  1506. vtor = validate.Validator()
  1507. # ini is your config file - cs is the configspec
  1508. cfg = ConfigObj(ini, configspec=cs)
  1509. res = cfg.validate(vtor, preserve_errors=True)
  1510. for entry in flatten_errors(cfg, res):
  1511. # each entry is a tuple
  1512. section_list, key, error = entry
  1513. if key is not None:
  1514. section_list.append(key)
  1515. else:
  1516. section_list.append('[missing section]')
  1517. section_string = ', '.join(section_list)
  1518. if error == False:
  1519. error = 'Missing value or section.'
  1520. print section_string, ' = ', error
  1521. get_extra_values
  1522. ================
  1523. .. code-block:: python
  1524. get_extra_values(conf)
  1525. New in ConfigObj 4.7.0.
  1526. Find all the values and sections not in the configspec from a validated
  1527. ConfigObj.
  1528. ``get_extra_values`` returns a list of tuples where each tuple represents
  1529. either an extra section, or an extra value.
  1530. The tuples contain two values, a tuple representing the section the value
  1531. is in and the name of the extra values. For extra values in the top level
  1532. section the first member will be an empty tuple. For values in the 'foo'
  1533. section the first member will be ``('foo',)``. For members in the 'bar'
  1534. subsection of the 'foo' section the first member will be ``('foo', 'bar')``.
  1535. Extra sections will only have one entry. Values and subsections inside
  1536. an extra section aren't listed separately.
  1537. NOTE: If you call ``get_extra_values`` on a ConfigObj instance that hasn't
  1538. been validated it will return an empty list.
  1539. Example Usage
  1540. -------------
  1541. The output from ``get_extra_values`` is a list of tuples.
  1542. Here is an example of how you could present this information to the user.
  1543. .. code-block:: python
  1544. vtor = validate.Validator()
  1545. # ini is your config file - cs is the configspec
  1546. cfg = ConfigObj(ini, configspec=cs)
  1547. cfg.validate(vtor, preserve_errors=True)
  1548. for sections, name in get_extra_values(cfg):
  1549. # this code gets the extra values themselves
  1550. the_section = cfg
  1551. for section in sections:
  1552. the_section = cfg[section]
  1553. # the_value may be a section or a value
  1554. the_value = the_section[name]
  1555. section_or_value = 'value
  1556. if isinstance(the_value, dict):
  1557. # Sections are subclasses of dict
  1558. section_or_value = 'section'
  1559. section_string = ', '.join(sections) or "top level"
  1560. print 'Extra entry in section: %s. Entry %r is a %s' % (section_string, name, section_or_value)
  1561. CREDITS
  1562. =======
  1563. ConfigObj 4 is written by (and copyright) `Michael Foord`_ and
  1564. `Nicola Larosa`_.
  1565. Particularly thanks to Nicola Larosa for help on the config file spec, the
  1566. validation system and the doctests.
  1567. *validate.py* was originally written by Michael Foord and Mark Andrews.
  1568. Thanks to many others for input, patches and bugfixes.
  1569. LICENSE
  1570. =======
  1571. ConfigObj, and related files, are licensed under the BSD license. This is a
  1572. very unrestrictive license, but it comes with the usual disclaimer. This is
  1573. free software: test it, break it, just don't blame us if it eats your data !
  1574. Of course if it does, let us know and we'll fix the problem so it doesn't
  1575. happen to anyone else::
  1576. Copyright (c) 2004 - 2010, Michael Foord & Nicola Larosa
  1577. All rights reserved.
  1578. Redistribution and use in source and binary forms, with or without
  1579. modification, are permitted provided that the following conditions are
  1580. met:
  1581. * Redistributions of source code must retain the above copyright
  1582. notice, this list of conditions and the following disclaimer.
  1583. * Redistributions in binary form must reproduce the above
  1584. copyright notice, this list of conditions and the following
  1585. disclaimer in the documentation and/or other materials provided
  1586. with the distribution.
  1587. * Neither the name of Michael Foord nor Nicola Larosa
  1588. may be used to endorse or promote products derived from this
  1589. software without specific prior written permission.
  1590. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1591. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1592. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1593. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1594. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1595. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1596. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1597. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1598. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1599. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1600. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1601. You should also be able to find a copy of this license at : `BSD License`_
  1602. .. _BSD License: http://www.voidspace.org.uk/python/license.shtml
  1603. TODO
  1604. ====
  1605. Better support for configuration from multiple files, including tracking
  1606. *where* the original file came from and writing changes to the correct
  1607. file.
  1608. Make ``newline`` a keyword argument (as well as an attribute) ?
  1609. ``UTF16`` encoded files, when returned as a list of lines, will have the
  1610. BOM at the start of every line. Should this be removed from all but the
  1611. first line ?
  1612. Option to set warning type for unicode decode ? (Defaults to strict).
  1613. A method to optionally remove uniform indentation from multiline values.
  1614. (do as an example of using ``walk`` - along with string-escape)
  1615. Should the results dictionary from validate be an ordered dictionary if
  1616. `odict <http://www.voidspace.org.uk/python/odict.html>`_ is available ?
  1617. Implement some of the sequence methods (which include slicing) from the
  1618. newer ``odict`` ?
  1619. Preserve line numbers of values (and possibly the original text of each value).
  1620. ISSUES
  1621. ======
  1622. .. note::
  1623. Please file any bug reports to `Michael Foord`_ or the **ConfigObj**
  1624. `Mailing List`_.
  1625. There is currently no way to specify the encoding of a configspec file.
  1626. As a consequence of the changes to configspec handling in version 4.6.0, when
  1627. you create a ConfigObj instance and provide a configspec, the configspec
  1628. attribute is only set on the ConfigObj instance - it isn't set on the sections until you validate. You also can't set the configspec attribute to be a dictionary. This wasn't documented but did work previously.
  1629. In order to fix the problem with hashes in configspecs I had to turn off the parsing of inline comments in configspecs. This will only affect you if you are using ``copy=True`` when validating and expecting inline comments to be copied from the configspec into the ConfigObj instance (all other comments will be copied as usual).
  1630. If you *create* the configspec by passing in a ConfigObj instance (usual way is to pass in a filename or list of lines) then you should pass in ``_inspec=True`` to the constructor to allow hashes in values. This is the magic that switches off inline comment parsing.
  1631. When using ``copy`` mode for validation, it won't copy ``DEFAULT``
  1632. sections. This is so that you *can* use interpolation in configspec
  1633. files. This is probably true even if interpolation is off in the
  1634. configspec.
  1635. You can't have a keyword with the same name as a section (in the same
  1636. section). They are both dictionary keys - so they would overlap.
  1637. ConfigObj doesn't quote and unquote values if ``list_values=False``.
  1638. This means that leading or trailing whitespace in values will be lost when
  1639. writing. (Unless you manually quote).
  1640. Interpolation checks first the current section, then the 'DEFAULT' subsection
  1641. of the current section, before moving on to the current section's parent and
  1642. so on up the tree.
  1643. Does it matter that we don't support the ':' divider, which is supported
  1644. by ``ConfigParser`` ?
  1645. String interpolation and validation don't play well together. When
  1646. validation changes type it sets the value. This will correctly fetch the
  1647. value using interpolation - but then overwrite the interpolation reference.
  1648. If the value is unchanged by validation (it's a string) - but other types
  1649. will be.
  1650. CHANGELOG
  1651. =========
  1652. This is an abbreviated changelog showing the major releases up to version 4.
  1653. From version 4 it lists all releases and changes.
  1654. 2010/02/27 - Version 4.7.2
  1655. --------------------------
  1656. * BUGFIX: Restore Python 2.3 compatibility
  1657. * BUGFIX: Members that were lists were being returned as copies due to interpolation
  1658. introduced in 4.7. Lists are now only copies if interpolation changes a list
  1659. member.
  1660. * BUGFIX: ``pop`` now does interpolation in list values as well.
  1661. * BUGFIX: where interpolation matches a section name rather than a value it is
  1662. ignored instead of raising an exception on fetching the item.
  1663. * BUGFIX: values that use interpolation to reference members that don't exist can
  1664. now be repr'd.
  1665. * BUGFIX: Fix to avoid writing '\\r\\r\\n' on Windows when given a file opened in
  1666. text write mode ('w').
  1667. See `String Interpolation and List Values`_ for information about the problem with lists and interpolation.
  1668. 2010/02/06 - Version 4.7.1
  1669. --------------------------
  1670. * Fix bug in options deprecation warning added in 4.7.0
  1671. 2010/01/09 - Version 4.7.0
  1672. --------------------------
  1673. * Minimum supported version of Python is now 2.3
  1674. * ~25% performance improvement thanks to Christian Heimes
  1675. * String interpolation now works in list value members
  1676. * After validation any additional entries not in the configspec are listed in
  1677. the ``extra_values`` section member
  1678. * Addition of the ``get_extra_values`` function for finding all extra values
  1679. in a validated ConfigObj instance
  1680. * Deprecated the use of the ``options`` dictionary in the ConfigObj constructor
  1681. and added explicit keyword arguments instead. Use \*\*options if you want
  1682. to initialise a ConfigObj instance from a dictionary
  1683. * Constructing a ConfigObj from an existing ConfigObj instance now preserves
  1684. the order of values and sections from the original instance in the new one
  1685. * BUGFIX: Checks that failed validation would not populate ``default_values`` and
  1686. ``restore_default_value()`` wouldn't work for those entries
  1687. * BUGFIX: clear() now clears 'defaults'
  1688. * BUGFIX: empty values in list values were accidentally valid syntax. They now
  1689. raise a ``ParseError``. e.g. "value = 1, , 2"
  1690. * BUGFIX: Change to the result of a call to ``validate`` when ``preserve_errors``
  1691. is True. Previously sections where *all* values failed validation would
  1692. return False for the section rather than preserving the errors. False will
  1693. now only be returned for a section if it is missing
  1694. * Distribution includes version 1.0.1 of validate.py
  1695. * Removed __revision__ and __docformat__
  1696. 2009/04/13 - Version 4.6.0
  1697. --------------------------
  1698. * Pickling of ConfigObj instances now supported (thanks to Christian Heimes)
  1699. * Hashes in confgspecs are now allowed (see note below)
  1700. * Replaced use of hasattr (which can swallow exceptions) with getattr
  1701. * __many__ in configspecs can refer to scalars (ordinary values) as well as sections
  1702. * You can use ___many___ (three underscores!) where you want to use __many__ as well
  1703. * You can now have normal sections inside configspec sections that use __many__
  1704. * You can now create an empty ConfigObj with a configspec, programmatically set values and then validate
  1705. * A section that was supplied as a value (or vice-versa) in the actual config file would cause an exception during validation (the config file is still broken of course, but it is now handled gracefully)
  1706. * Added ``as_list`` method
  1707. * Removed the deprecated ``istrue``, ``encode`` and ``decode`` methods
  1708. * Running test_configobj.py now also runs the doctests in the configobj module
  1709. As a consequence of the changes to configspec handling, when you create a ConfigObj instance and provide
  1710. a configspec, the configspec attribute is only set on the ConfigObj instance - it isn't set on the
  1711. sections until you validate. You also can't set the configspec attribute to be a dictionary. This wasn't
  1712. documented but did work previously.
  1713. In order to fix the problem with hashes in configspecs I had to turn off the parsing of inline comments
  1714. in configspecs. This will only affect you if you are using ``copy=True`` when validating and expecting
  1715. inline comments to be copied from the configspec into the ConfigObj instance (all other comments will be
  1716. copied as usual).
  1717. If you *create* the configspec by passing in a ConfigObj instance (usual way is to pass in a filename or
  1718. list of lines) then you should pass in ``_inspec=True`` to the constructor to allow hashes in values.
  1719. This is the magic that switches off inline comment parsing.
  1720. 2008/06/27 - Version 4.5.3
  1721. --------------------------
  1722. BUGFIX: fixed a problem with ``copy=True`` when validating with configspecs that use
  1723. ``__many__`` sections.
  1724. 2008/02/05 - Version 4.5.2
  1725. --------------------------
  1726. Distribution updated to include version 0.3.2 of validate_. This means that
  1727. ``None`` as a default value in configspecs works.
  1728. 2008/02/05 - Version 4.5.1
  1729. --------------------------
  1730. Distribution updated to include version 0.3.1 of validate_. This means that
  1731. Unicode configspecs now work.
  1732. 2008/02/05 - Version 4.5.0
  1733. --------------------------
  1734. ConfigObj will now guarantee that files will be written terminated with a
  1735. newline.
  1736. ConfigObj will no longer attempt to import the ``validate`` module, until/unless
  1737. you call ``ConfigObj.validate`` with ``preserve_errors=True``. This makes it
  1738. faster to import.
  1739. New methods ``restore_default`` and ``restore_defaults``. ``restore_default``
  1740. resets an entry to its default value (and returns that value). ``restore_defaults``
  1741. resets all entries to their default value. It doesn't modify entries without a
  1742. default value. You must have validated a ConfigObj (which populates the
  1743. ``default_values`` dictionary) before calling these methods.
  1744. BUGFIX: Proper quoting of keys, values and list values that contain hashes
  1745. (when writing). When ``list_values=False``, values containing hashes are
  1746. triple quoted.
  1747. Added the ``reload`` method. This reloads a ConfigObj from file. If the filename
  1748. attribute is not set then a ``ReloadError`` (a new exception inheriting from
  1749. ``IOError``) is raised.
  1750. BUGFIX: Files are read in with 'rb' mode, so that native/non-native line endings work!
  1751. Minor efficiency improvement in ``unrepr`` mode.
  1752. Added missing docstrings for some overidden dictionary methods.
  1753. Added the ``reset`` method. This restores a ConfigObj to a freshly created state.
  1754. Removed old CHANGELOG file.
  1755. 2007/02/04 - Version 4.4.0
  1756. --------------------------
  1757. Official release of 4.4.0
  1758. 2006/12/17 - Version 4.3.3-alpha4
  1759. ---------------------------------
  1760. By Nicola Larosa
  1761. Allowed arbitrary indentation in the ``indent_type`` parameter, removed the
  1762. ``NUM_INDENT_SPACES`` and ``MAX_INTERPOL_DEPTH`` (a leftover) constants,
  1763. added indentation tests (including another docutils workaround, sigh), updated
  1764. the documentation.
  1765. By Michael Foord
  1766. Made the import of ``compiler`` conditional so that ``ConfigObj`` can be used
  1767. with `IronPython <http://www.codeplex.com/IronPython>`_.
  1768. 2006/12/17 - Version 4.3.3-alpha3
  1769. ---------------------------------
  1770. By Nicola Larosa
  1771. Added a missing ``self.`` in the _handle_comment method and a related test,
  1772. per Sourceforge bug #1523975.
  1773. 2006/12/09 - Version 4.3.3-alpha2
  1774. ---------------------------------
  1775. By Nicola Larosa
  1776. Changed interpolation search strategy, based on this patch by Robin Munn:
  1777. http://sourceforge.net/mailarchive/message.php?msg_id=17125993
  1778. 2006/12/09 - Version 4.3.3-alpha1
  1779. ---------------------------------
  1780. By Nicola Larosa
  1781. Added Template-style interpolation, with tests, based on this patch by
  1782. Robin Munn: http://sourceforge.net/mailarchive/message.php?msg_id=17125991
  1783. (awful archives, bad Sourceforge, bad).
  1784. 2006/06/04 - Version 4.3.2
  1785. --------------------------
  1786. Changed error handling, if parsing finds a single error then that error will
  1787. be re-raised. That error will still have an ``errors`` and a ``config``
  1788. attribute.
  1789. Fixed bug where '\\n' terminated files could be truncated.
  1790. Bugfix in ``unrepr`` mode, it couldn't handle '#' in values. (Thanks to
  1791. Philippe Normand for the report.)
  1792. As a consequence of this fix, ConfigObj doesn't now keep inline comments in
  1793. ``unrepr`` mode. This is because the parser in the `compiler package`_
  1794. doesn't keep comments.
  1795. Error messages are now more useful. They tell you the number of parsing errors
  1796. and the line number of the first error. (In the case of multiple errors.)
  1797. Line numbers in exceptions now start at 1, not 0.
  1798. Errors in ``unrepr`` mode are now handled the same way as in the normal mode.
  1799. The errors stored will be an ``UnreprError``.
  1800. 2006/04/29 - Version 4.3.1
  1801. --------------------------
  1802. Added ``validate.py`` back into ``configobj.zip``. (Thanks to Stewart
  1803. Midwinter)
  1804. Updated to `validate.py`_ 0.2.2.
  1805. Preserve tuples when calling the ``dict`` method. (Thanks to Gustavo Niemeyer.)
  1806. Changed ``__repr__`` to return a string that contains ``ConfigObj({ ... })``.
  1807. Change so that an options dictionary isn't modified by passing it to ConfigObj.
  1808. (Thanks to Artarious.)
  1809. Added ability to handle negative integers in ``unrepr``. (Thanks to Kevin
  1810. Dangoor.)
  1811. 2006/03/24 - Version 4.3.0
  1812. --------------------------
  1813. Moved the tests and the CHANGELOG (etc) into a separate file. This has reduced
  1814. the size of ``configobj.py`` by about 40%.
  1815. Added the ``unrepr`` mode to reading and writing config files. Thanks to Kevin
  1816. Dangoor for this suggestion.
  1817. Empty values are now valid syntax. They are read as an empty string ``''``.
  1818. (``key =``, or ``key = # comment``.)
  1819. ``validate`` now honours the order of the configspec.
  1820. Added the ``copy`` mode to validate. Thanks to Louis Cordier for this
  1821. suggestion.
  1822. Fixed bug where files written on windows could be given ``'\r\r\n'`` line
  1823. terminators.
  1824. Fixed bug where last occurring comment line could be interpreted as the
  1825. final comment if the last line isn't terminated.
  1826. Fixed bug where nested list values would be flattened when ``write`` is
  1827. called. Now sub-lists have a string representation written instead.
  1828. Deprecated ``encode`` and ``decode`` methods instead.
  1829. You can now pass in a ConfigObj instance as a configspec (remember to read
  1830. the configspec file using ``list_values=False``).
  1831. Sorted footnotes in the docs.
  1832. 2006/02/16 - Version 4.2.0
  1833. --------------------------
  1834. Removed ``BOM_UTF8`` from ``__all__``.
  1835. The ``BOM`` attribute has become a boolean. (Defaults to ``False``.) It is
  1836. *only* ``True`` for the ``UTF16/UTF8`` encodings.
  1837. File like objects no longer need a ``seek`` attribute.
  1838. Full unicode support added. New options/attributes ``encoding``,
  1839. ``default_encoding``.
  1840. ConfigObj no longer keeps a reference to file like objects. Instead the
  1841. ``write`` method takes a file like object as an optional argument. (Which
  1842. will be used in preference of the ``filename`` attribute if that exists as
  1843. well.)
  1844. utf16 files decoded to unicode.
  1845. If ``BOM`` is ``True``, but no encoding specified, then the utf8 BOM is
  1846. written out at the start of the file. (It will normally only be ``True`` if
  1847. the utf8 BOM was found when the file was read.)
  1848. Thanks to Aaron Bentley for help and testing on the unicode issues.
  1849. File paths are *not* converted to absolute paths, relative paths will
  1850. remain relative as the ``filename`` attribute.
  1851. Fixed bug where ``final_comment`` wasn't returned if ``write`` is returning
  1852. a list of lines.
  1853. Deprecated ``istrue``, replaced it with ``as_bool``.
  1854. Added ``as_int`` and ``as_float``.
  1855. 2005/12/14 - Version 4.1.0
  1856. --------------------------
  1857. Added ``merge``, a recursive update.
  1858. Added ``preserve_errors`` to ``validate`` and the ``flatten_errors``
  1859. example function.
  1860. Thanks to Matthew Brett for suggestions and helping me iron out bugs.
  1861. Fixed bug where a config file is *all* comment, the comment will now be
  1862. ``initial_comment`` rather than ``final_comment``.
  1863. Validation no longer done on the 'DEFAULT' section (only in the root level).
  1864. This allows interpolation in configspecs.
  1865. Also use the new list syntax in validate_ 0.2.1. (For configspecs).
  1866. 2005/12/02 - Version 4.0.2
  1867. --------------------------
  1868. Fixed bug in ``create_empty``. Thanks to Paul Jimenez for the report.
  1869. 2005/11/05 - Version 4.0.1
  1870. --------------------------
  1871. Fixed bug in ``Section.walk`` when transforming names as well as values.
  1872. Added the ``istrue`` method. (Fetches the boolean equivalent of a string
  1873. value).
  1874. Fixed ``list_values=False`` - they are now only quoted/unquoted if they
  1875. are multiline values.
  1876. List values are written as ``item, item`` rather than ``item,item``.
  1877. 2005/10/17 - Version 4.0.0
  1878. --------------------------
  1879. **ConfigObj 4.0.0 Final**
  1880. Fixed bug in ``setdefault``. When creating a new section with setdefault the
  1881. reference returned would be to the dictionary passed in *not* to the new
  1882. section. Bug fixed and behaviour documented.
  1883. Obscure typo/bug fixed in ``write``. Wouldn't have affected anyone though.
  1884. 2005/09/09 - Version 4.0.0 beta 5
  1885. ---------------------------------
  1886. Removed ``PositionError``.
  1887. Allowed quotes around keys as documented.
  1888. Fixed bug with commas in comments. (matched as a list value)
  1889. 2005/09/07 - Version 4.0.0 beta 4
  1890. ---------------------------------
  1891. Fixed bug in ``__delitem__``. Deleting an item no longer deletes the
  1892. ``inline_comments`` attribute.
  1893. Fixed bug in initialising ConfigObj from a ConfigObj.
  1894. Changed the mailing list address.
  1895. 2005/08/28 - Version 4.0.0 beta 3
  1896. ---------------------------------
  1897. Interpolation is switched off before writing out files.
  1898. Fixed bug in handling ``StringIO`` instances. (Thanks to report from
  1899. Gustavo Niemeyer.)
  1900. Moved the doctests from the ``__init__`` method to a separate function.
  1901. (For the sake of IDE calltips).
  1902. 2005/08/25 - Version 4.0.0 beta 2
  1903. ---------------------------------
  1904. Amendments to *validate.py*.
  1905. First public release.
  1906. 2005/08/21 - Version 4.0.0 beta 1
  1907. ---------------------------------
  1908. Reads nested subsections to any depth.
  1909. Multiline values.
  1910. Simplified options and methods.
  1911. New list syntax.
  1912. Faster, smaller, and better parser.
  1913. Validation greatly improved. Includes:
  1914. * type conversion
  1915. * default values
  1916. * repeated sections
  1917. Improved error handling.
  1918. Plus lots of other improvements.
  1919. 2004/05/24 - Version 3.0.0
  1920. --------------------------
  1921. Several incompatible changes: another major overhaul and change. (Lots of
  1922. improvements though).
  1923. Added support for standard config files with sections. This has an entirely
  1924. new interface: each section is a dictionary of values.
  1925. Changed the update method to be called writein: update clashes with a dict
  1926. method.
  1927. Made various attributes keyword arguments, added several.
  1928. Configspecs and orderlists have changed a great deal.
  1929. Removed support for adding dictionaries: use update instead.
  1930. Now subclasses a new class called caselessDict. This should add various
  1931. dictionary methods that could have caused errors before.
  1932. It also preserves the original casing of keywords when writing them back out.
  1933. Comments are also saved using a ``caselessDict``.
  1934. Using a non-string key will now raise a ``TypeError`` rather than converting
  1935. the key.
  1936. Added an exceptions keyword for *much* better handling of errors.
  1937. Made ``creatempty=False`` the default.
  1938. Now checks indict *and* any keyword args. Keyword args take precedence over
  1939. indict.
  1940. ``' ', ':', '=', ','`` and ``'\t'`` are now all valid dividers where the
  1941. keyword is unquoted.
  1942. ConfigObj now does no type checking against configspec when you set items.
  1943. delete and add methods removed (they were unnecessary).
  1944. Docs rewritten to include all this gumph and more; actually ConfigObj is
  1945. *really* easy to use.
  1946. Support for stdout was removed.
  1947. A few new methods added.
  1948. Charmap is now incorporated into ConfigObj.
  1949. 2004/03/14 - Version 2.0.0 beta
  1950. -------------------------------
  1951. Re-written it to subclass dict. My first forays into inheritance and operator
  1952. overloading.
  1953. The config object now behaves like a dictionary.
  1954. I've completely broken the interface, but I don't think anyone was really
  1955. using it anyway.
  1956. This new version is much more 'classy'.
  1957. It will also read straight from/to a filename and completely parse a config
  1958. file without you *having* to supply a config spec.
  1959. Uses listparse, so can handle nested list items as values.
  1960. No longer has getval and setval methods: use normal dictionary methods, or add
  1961. and delete.
  1962. 2004/01/29 - Version 1.0.5
  1963. --------------------------
  1964. Version 1.0.5 has a couple of bugfixes as well as a couple of useful additions
  1965. over previous versions.
  1966. Since 1.0.0 the buildconfig function has been moved into this distribution,
  1967. and the methods reset, verify, getval and setval have been added.
  1968. A couple of bugs have been fixed.
  1969. Origins
  1970. -------
  1971. ConfigObj originated in a set of functions for reading config files in the
  1972. `atlantibots <http://www.voidspace.org.uk/atlantibots/>`_ project. The original
  1973. functions were written by Rob McNeur.
  1974. ----------
  1975. Footnotes
  1976. =========
  1977. .. [#] And if you discover any bugs, let us know. We'll fix them quickly.
  1978. .. [#] If you specify a filename that doesn't exist, ConfigObj will assume you
  1979. are creating a new one. See the *create_empty* and *file_error* options.
  1980. .. [#] They can be byte strings (*ordinary* strings) or Unicode.
  1981. .. [#] Except we don't support the RFC822 style line continuations, nor ':' as
  1982. a divider.
  1983. .. [#] This is a change in ConfigObj 4.2.0. Note that ConfigObj doesn't call
  1984. the seek method of any file like object you pass in. You may want to call
  1985. ``file_object.seek(0)`` yourself, first.
  1986. .. [#] A side effect of this is that it enables you to copy a ConfigObj :
  1987. .. code-block:: python
  1988. # only copies members
  1989. # not attributes/comments
  1990. config2 = ConfigObj(config1)
  1991. Since ConfigObj 4.7.0 the order of members and sections will be
  1992. preserved when copying a ConfigObj instance.
  1993. .. [#] Other than lists of strings.
  1994. .. [#] The exception is if it detects a ``UTF16`` encoded file which it
  1995. must decode before parsing.
  1996. .. [#] The method signature shows that this method takes
  1997. two arguments. The second is the section to be written. This is because the
  1998. ``write`` method is called recursively.
  1999. .. [#] The dict method doesn't actually use the deepcopy mechanism. This means
  2000. if you add nested lists (etc) to your ConfigObj, then the dictionary
  2001. returned by dict may contain some references. For all *normal* ConfigObjs
  2002. it will return a deepcopy.
  2003. .. [#] Passing ``(section, key)`` rather than ``(value, key)`` allows you to
  2004. change the value by setting ``section[key] = newval``. It also gives you
  2005. access to the *rename* method of the section.
  2006. .. [#] Minimum required version of *validate.py* 0.2.0 .
  2007. .. _listquote: http://www.voidspace.org.uk/python/modules.shtml#listquote
  2008. .. _Michael Foord: http://www.voidspace.org.uk/python/weblog/index.shtml
  2009. .. _Nicola Larosa: http://www.teknico.net