Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7f64c8a

Browse files
committed
Broken ConfigParser removed, SafeConfigParser renamed to ConfigParser.
Life is beatiful once again.
1 parent bb9686f commit 7f64c8a

3 files changed

Lines changed: 155 additions & 202 deletions

File tree

Doc/library/configparser.rst

Lines changed: 39 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@
1717
single: ini file
1818
single: Windows ini file
1919

20-
This module provides the :class:`SafeConfigParser` class which implements
21-
a basic configuration language which provides a structure similar to what's
22-
found in Microsoft Windows INI files. You can use this to write Python
23-
programs which can be customized by end users easily.
20+
This module provides the :class:`ConfigParser` class which implements a basic
21+
configuration language which provides a structure similar to what's found in
22+
Microsoft Windows INI files. You can use this to write Python programs which
23+
can be customized by end users easily.
2424

2525
.. note::
2626

@@ -67,7 +67,7 @@ creating the above configuration file programatically.
6767
.. doctest::
6868

6969
>>> import configparser
70-
>>> config = configparser.SafeConfigParser()
70+
>>> config = configparser.ConfigParser()
7171
>>> config['DEFAULT'] = {'ServerAliveInterval': '45',
7272
... 'Compression': 'yes',
7373
... 'CompressionLevel': '9'}
@@ -92,7 +92,7 @@ back and explore the data it holds.
9292
.. doctest::
9393

9494
>>> import configparser
95-
>>> config = configparser.SafeConfigParser()
95+
>>> config = configparser.ConfigParser()
9696
>>> config.sections()
9797
[]
9898
>>> config.read('example.ini')
@@ -283,13 +283,13 @@ For example:
283283
Interpolation of values
284284
-----------------------
285285

286-
On top of the core functionality, :class:`SafeConfigParser` supports
286+
On top of the core functionality, :class:`ConfigParser` supports
287287
interpolation. This means values can be preprocessed before returning them
288288
from ``get()`` calls.
289289

290290
.. class:: BasicInterpolation()
291291

292-
The default implementation used by :class:`SafeConfigParser`. It enables
292+
The default implementation used by :class:`ConfigParser`. It enables
293293
values to contain format strings which refer to other values in the same
294294
section, or values in the special default section [1]_. Additional default
295295
values can be provided on initialization.
@@ -304,7 +304,7 @@ from ``get()`` calls.
304304
my_pictures: %(my_dir)s/Pictures
305305
306306
307-
In the example above, :class:`SafeConfigParser` with *interpolation* set to
307+
In the example above, :class:`ConfigParser` with *interpolation* set to
308308
``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of
309309
``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in effect would
310310
resolve to ``/Users/lumberjack``. All interpolations are done on demand so
@@ -444,7 +444,7 @@ the :meth:`__init__` options:
444444

445445
.. doctest::
446446

447-
>>> parser = configparser.SafeConfigParser()
447+
>>> parser = configparser.ConfigParser()
448448
>>> parser.read_dict({'section1': {'key1': 'value1',
449449
... 'key2': 'value2',
450450
... 'key3': 'value3'},
@@ -465,7 +465,7 @@ the :meth:`__init__` options:
465465
.. doctest::
466466

467467
>>> from collections import OrderedDict
468-
>>> parser = configparser.SafeConfigParser()
468+
>>> parser = configparser.ConfigParser()
469469
>>> parser.read_dict(
470470
... OrderedDict((
471471
... ('s1',
@@ -511,7 +511,7 @@ the :meth:`__init__` options:
511511
... skip-bdb
512512
... skip-innodb # we don't need ACID today
513513
... """
514-
>>> config = configparser.SafeConfigParser(allow_no_value=True)
514+
>>> config = configparser.ConfigParser(allow_no_value=True)
515515
>>> config.read_string(sample_config)
516516

517517
>>> # Settings with values are treated as before:
@@ -534,7 +534,7 @@ the :meth:`__init__` options:
534534
This means values (but not keys) can contain the delimiters.
535535

536536
See also the *space_around_delimiters* argument to
537-
:meth:`SafeConfigParser.write`.
537+
:meth:`ConfigParser.write`.
538538

539539
* *comment_prefixes*, default value: ``_COMPATIBLE`` (``'#'`` valid on empty
540540
lines, ``';'`` valid also on non-empty lines)
@@ -604,8 +604,7 @@ the :meth:`__init__` options:
604604
advanced variant inspired by ``zc.buildout``. More on the subject in the
605605
`dedicated documentation section <#interpolation-of-values>`_.
606606

607-
.. note:: :class:`RawConfigParser` is using ``None`` by default and
608-
:class:`ConfigParser` is using ``configparser.BrokenInterpolation``.
607+
.. note:: :class:`RawConfigParser` is using ``None`` by default.
609608

610609

611610
More advanced customization may be achieved by overriding default values of
@@ -622,7 +621,7 @@ may be overriden by subclasses or by attribute assignment.
622621

623622
.. doctest::
624623

625-
>>> custom = configparser.SafeConfigParser()
624+
>>> custom = configparser.ConfigParser()
626625
>>> custom['section1'] = {'funky': 'nope'}
627626
>>> custom['section1'].getboolean('funky')
628627
Traceback (most recent call last):
@@ -652,7 +651,7 @@ may be overriden by subclasses or by attribute assignment.
652651
... [Section2]
653652
... AnotherKey = Value
654653
... """
655-
>>> typical = configparser.SafeConfigParser()
654+
>>> typical = configparser.ConfigParser()
656655
>>> typical.read_string(config)
657656
>>> list(typical['Section1'].keys())
658657
['key']
@@ -670,24 +669,23 @@ may be overriden by subclasses or by attribute assignment.
670669
Legacy API Examples
671670
-------------------
672671

673-
Mainly because of backwards compatibility concerns, :mod:`configparser` provides
674-
also a legacy API with explicit ``get``/``set`` methods. While there are valid
675-
use cases for the methods outlined below, mapping protocol access is preferred
676-
for new projects. The legacy API is at times more advanced, low-level and
677-
downright counterintuitive.
672+
Mainly because of backwards compatibility concerns, :mod:`configparser`
673+
provides also a legacy API with explicit ``get``/``set`` methods. While there
674+
are valid use cases for the methods outlined below, mapping protocol access is
675+
preferred for new projects. The legacy API is at times more advanced,
676+
low-level and downright counterintuitive.
678677

679678
An example of writing to a configuration file::
680679

681680
import configparser
682681

683682
config = configparser.RawConfigParser()
684683

685-
# Please note that using RawConfigParser's and the raw mode of
686-
# ConfigParser's respective set functions, you can assign non-string values
687-
# to keys internally, but will receive an error when attempting to write to
688-
# a file or when you get it in non-raw mode. Setting values using the
689-
# mapping protocol or SafeConfigParser's set() does not allow such
690-
# assignments to take place.
684+
# Please note that using RawConfigParser's set functions, you can assign
685+
# non-string values to keys internally, but will receive an error when
686+
# attempting to write to a file or when you get it in non-raw mode. Setting
687+
# values using the mapping protocol or ConfigParser's set() does not allow
688+
# such assignments to take place.
691689
config.add_section('Section1')
692690
config.set('Section1', 'int', '15')
693691
config.set('Section1', 'bool', 'true')
@@ -718,11 +716,11 @@ An example of reading the configuration file again::
718716
if config.getboolean('Section1', 'bool'):
719717
print(config.get('Section1', 'foo'))
720718

721-
To get interpolation, use :class:`SafeConfigParser`::
719+
To get interpolation, use :class:`ConfigParser`::
722720

723721
import configparser
724722

725-
cfg = configparser.SafeConfigParser()
723+
cfg = configparser.ConfigParser()
726724
cfg.read('example.cfg')
727725

728726
# Set the optional `raw` argument of get() to True if you wish to disable
@@ -751,13 +749,13 @@ To get interpolation, use :class:`SafeConfigParser`::
751749
print(cfg.get('Section1', 'monster', fallback=None))
752750
# -> None
753751

754-
Default values are available in all three types of ConfigParsers. They are
755-
used in interpolation if an option used is not defined elsewhere. ::
752+
Default values are available in both types of ConfigParsers. They are used in
753+
interpolation if an option used is not defined elsewhere. ::
756754

757755
import configparser
758756

759757
# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
760-
config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
758+
config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
761759
config.read('example.cfg')
762760

763761
print(config.get('Section1', 'foo')) # -> "Python is fun!"
@@ -766,12 +764,12 @@ used in interpolation if an option used is not defined elsewhere. ::
766764
print(config.get('Section1', 'foo')) # -> "Life is hard!"
767765

768766

769-
.. _safeconfigparser-objects:
767+
.. _configparser-objects:
770768

771-
SafeConfigParser Objects
772-
------------------------
769+
ConfigParser Objects
770+
--------------------
773771

774-
.. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation())
772+
.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation())
775773

776774
The main configuration parser. When *defaults* is given, it is initialized
777775
into the dictionary of intrinsic defaults. When *dict_type* is given, it
@@ -877,7 +875,7 @@ SafeConfigParser Objects
877875

878876
import configparser, os
879877

880-
config = configparser.SafeConfigParser()
878+
config = configparser.ConfigParser()
881879
config.read_file(open('defaults.cfg'))
882880
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
883881
encoding='cp1250')
@@ -1047,13 +1045,13 @@ RawConfigParser Objects
10471045

10481046
.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True, default_section=configaparser.DEFAULTSECT, interpolation=None)
10491047

1050-
Legacy variant of the :class:`SafeConfigParser` with interpolation disabled
1048+
Legacy variant of the :class:`ConfigParser` with interpolation disabled
10511049
by default and unsafe ``add_section`` and ``set`` methods.
10521050

10531051
.. note::
1054-
Consider using :class:`SafeConfigParser` instead which checks types of
1052+
Consider using :class:`ConfigParser` instead which checks types of
10551053
the values to be stored internally. If you don't want interpolation, you
1056-
can use ``SafeConfigParser(interpolation=None)``.
1054+
can use ``ConfigParser(interpolation=None)``.
10571055

10581056

10591057
.. method:: add_section(section)
@@ -1081,25 +1079,6 @@ RawConfigParser Objects
10811079
which does not allow such assignments to take place.
10821080

10831081

1084-
.. _configparser-objects:
1085-
1086-
ConfigParser Objects
1087-
--------------------
1088-
1089-
.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BrokenInterpolation())
1090-
1091-
.. deprecated:: 3.2
1092-
Whenever you can, consider using :class:`SafeConfigParser`. The
1093-
:class:`ConfigParser` provides the same functionality but its
1094-
implementation is less predictable. It does not validate the
1095-
interpolation syntax used within a configuration file. It also does not
1096-
enable escaping the interpolation character (when using
1097-
:class:`SafeConfigParser`, a key can have ``%`` as part of the value by
1098-
specifying ``%%`` in the file). On top of that, this class doesn't ensure
1099-
whether values passed to the parser object are strings which may lead to
1100-
inconsistent internal state.
1101-
1102-
11031082
Exceptions
11041083
----------
11051084

Lib/configparser.py

Lines changed: 22 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@
55
the style of RFC 822.
66
77
Intrinsic defaults can be specified by passing them into the
8-
SafeConfigParser constructor as a dictionary.
8+
ConfigParser constructor as a dictionary.
99
1010
class:
1111
12-
SafeConfigParser -- responsible for parsing a list of
12+
ConfigParser -- responsible for parsing a list of
1313
configuration files, and managing the parsed database.
1414
1515
methods:
@@ -265,9 +265,8 @@ def __init__(self, option, section, rawval, reference):
265265
class InterpolationSyntaxError(InterpolationError):
266266
"""Raised when the source text contains invalid syntax.
267267
268-
Current implementation raises this exception only for SafeConfigParser
269-
instances when the source text into which substitutions are made
270-
does not conform to the required syntax.
268+
Current implementation raises this exception when the source text into
269+
which substitutions are made does not conform to the required syntax.
271270
"""
272271

273272

@@ -369,7 +368,7 @@ def before_write(self, parser, section, option, value):
369368

370369

371370
class BasicInterpolation(Interpolation):
372-
"""Interpolation as implemented in the classic SafeConfigParser.
371+
"""Interpolation as implemented in the classic ConfigParser.
373372
374373
The option values can contain format strings which refer to other values in
375374
the same section, or values in the special default section.
@@ -512,8 +511,8 @@ def _interpolate_some(self, parser, option, accum, rest, section, map,
512511
"found: %r" % (rest,))
513512

514513

515-
class BrokenInterpolation(Interpolation):
516-
"""Deprecated interpolation as implemented in the classic ConfigParser.
514+
class LegacyInterpolation(Interpolation):
515+
"""Deprecated interpolation used in old versions of ConfigParser.
517516
Use BasicInterpolation or ExtendedInterpolation instead."""
518517

519518
_KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
@@ -598,12 +597,6 @@ def __init__(self, defaults=None, dict_type=_default_dict,
598597
default_section=DEFAULTSECT,
599598
interpolation=_UNSET):
600599

601-
if self.__class__ is RawConfigParser:
602-
warnings.warn(
603-
"The RawConfigParser class will be removed in future versions."
604-
" Use 'SafeConfigParser(interpolation=None)' instead.",
605-
DeprecationWarning, stacklevel=2
606-
)
607600
self._dict = dict_type
608601
self._sections = self._dict()
609602
self._defaults = self._dict()
@@ -1142,8 +1135,8 @@ def _validate_value_types(self, *, section="", option="", value=""):
11421135
- we allow valueless options but the value is not None
11431136
11441137
For compatibility reasons this method is not used in classic set()
1145-
for RawConfigParsers and ConfigParsers. It is invoked in every
1146-
case for mapping protocol access and in SafeConfigParser.set().
1138+
for RawConfigParsers. It is invoked in every case for mapping protocol
1139+
access and in ConfigParser.set().
11471140
"""
11481141
if not isinstance(section, str):
11491142
raise TypeError("section names must be strings")
@@ -1157,21 +1150,6 @@ def _validate_value_types(self, *, section="", option="", value=""):
11571150
class ConfigParser(RawConfigParser):
11581151
"""ConfigParser implementing interpolation."""
11591152

1160-
_DEFAULT_INTERPOLATION = BrokenInterpolation()
1161-
1162-
def __init__(self, *args, **kwargs):
1163-
super().__init__(*args, **kwargs)
1164-
if self.__class__ is ConfigParser:
1165-
warnings.warn(
1166-
"The ConfigParser class will be removed in future versions."
1167-
" Use SafeConfigParser instead.",
1168-
DeprecationWarning, stacklevel=2
1169-
)
1170-
1171-
1172-
class SafeConfigParser(ConfigParser):
1173-
"""ConfigParser implementing sane interpolation."""
1174-
11751153
_DEFAULT_INTERPOLATION = BasicInterpolation()
11761154

11771155
def set(self, section, option, value=None):
@@ -1188,6 +1166,19 @@ def add_section(self, section):
11881166
super().add_section(section)
11891167

11901168

1169+
class SafeConfigParser(ConfigParser):
1170+
"""ConfigParser alias for backwards compatibility purposes."""
1171+
1172+
def __init__(self, *args, **kwargs):
1173+
super().__init__(*args, **kwargs)
1174+
warnings.warn(
1175+
"The SafeConfigParser class has been renamed to ConfigParser "
1176+
"in Python 3.2. This alias will be removed in future versions."
1177+
" Use ConfigParser directly instead.",
1178+
DeprecationWarning, stacklevel=2
1179+
)
1180+
1181+
11911182
class SectionProxy(MutableMapping):
11921183
"""A proxy for a single section from a parser."""
11931184

0 commit comments

Comments
 (0)