Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/nameparser/config/__init__.py: 78%
95 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:08 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:08 +0000
1# -*- coding: utf-8 -*-
2"""
3The :py:mod:`nameparser.config` module manages the configuration of the
4nameparser.
6A module-level instance of :py:class:`~nameparser.config.Constants` is created
7and used by default for all HumanName instances. You can adjust the entire module's
8configuration by importing this instance and changing it.
10::
12 >>> from nameparser.config import CONSTANTS
13 >>> CONSTANTS.titles.remove('hon').add('chemistry','dean') # doctest: +ELLIPSIS
14 SetManager(set([u'msgt', ..., u'adjutant']))
16You can also adjust the configuration of individual instances by passing
17``None`` as the second argument upon instantiation.
19::
21 >>> from nameparser import HumanName
22 >>> hn = HumanName("Dean Robert Johns", None)
23 >>> hn.C.titles.add('dean') # doctest: +ELLIPSIS
24 SetManager(set([u'msgt', ..., u'adjutant']))
25 >>> hn.parse_full_name() # need to run this again after config changes
27**Potential Gotcha**: If you do not pass ``None`` as the second argument,
28``hn.C`` will be a reference to the module config, possibly yielding
29unexpected results. See `Customizing the Parser <customize.html>`_.
30"""
31from __future__ import unicode_literals
32import sys
33try:
34 # Python 3.3+
35 from collections.abc import Set
36except ImportError:
37 from collections import Set
39from nameparser.util import binary_type
40from nameparser.util import lc
41from nameparser.config.prefixes import PREFIXES
42from nameparser.config.capitalization import CAPITALIZATION_EXCEPTIONS
43from nameparser.config.conjunctions import CONJUNCTIONS
44from nameparser.config.suffixes import SUFFIX_ACRONYMS
45from nameparser.config.suffixes import SUFFIX_NOT_ACRONYMS
46from nameparser.config.titles import TITLES
47from nameparser.config.titles import FIRST_NAME_TITLES
48from nameparser.config.regexes import REGEXES
50DEFAULT_ENCODING = 'UTF-8'
53class SetManager(Set):
54 '''
55 Easily add and remove config variables per module or instance. Subclass of
56 ``collections.abc.Set``.
58 Only special functionality beyond that provided by set() is
59 to normalize constants for comparison (lower case, no periods)
60 when they are add()ed and remove()d and allow passing multiple
61 string arguments to the :py:func:`add()` and :py:func:`remove()` methods.
63 '''
65 def __init__(self, elements):
66 self.elements = set(elements)
68 def __call__(self):
69 return self.elements
71 def __repr__(self):
72 return "SetManager({})".format(self.elements) # used for docs
74 def __iter__(self):
75 return iter(self.elements)
77 def __contains__(self, value):
78 return value in self.elements
80 def __len__(self):
81 return len(self.elements)
83 def next(self):
84 return self.__next__()
86 def __next__(self):
87 if self.count >= len(self.elements):
88 self.count = 0
89 raise StopIteration
90 else:
91 c = self.count
92 self.count = c + 1
93 return getattr(self, self.elements[c]) or next(self)
95 def add_with_encoding(self, s, encoding=None):
96 """
97 Add the lower case and no-period version of the string to the set. Pass an
98 explicit `encoding` parameter to specify the encoding of binary strings that
99 are not DEFAULT_ENCODING (UTF-8).
100 """
101 stdin_encoding = None
102 if sys.stdin:
103 stdin_encoding = sys.stdin.encoding
104 encoding = encoding or stdin_encoding or DEFAULT_ENCODING
105 if type(s) == binary_type:
106 s = s.decode(encoding)
107 self.elements.add(lc(s))
109 def add(self, *strings):
110 """
111 Add the lower case and no-period version of the string arguments to the set.
112 Can pass a list of strings. Returns ``self`` for chaining.
113 """
114 [self.add_with_encoding(s) for s in strings]
115 return self
117 def remove(self, *strings):
118 """
119 Remove the lower case and no-period version of the string arguments from the set.
120 Returns ``self`` for chaining.
121 """
122 [self.elements.remove(lc(s)) for s in strings if lc(s) in self.elements]
123 return self
126class TupleManager(dict):
127 '''
128 A dictionary with dot.notation access. Subclass of ``dict``. Makes the tuple constants
129 more friendly.
130 '''
132 def __getattr__(self, attr):
133 return self.get(attr)
134 __setattr__ = dict.__setitem__
135 __delattr__ = dict.__delitem__
137 def __getstate__(self):
138 return dict(self)
140 def __setstate__(self, state):
141 self.__init__(state)
143 def __reduce__(self):
144 return (TupleManager, (), self.__getstate__())
147class Constants(object):
148 """
149 An instance of this class hold all of the configuration constants for the parser.
151 :param set prefixes:
152 :py:attr:`prefixes` wrapped with :py:class:`SetManager`.
153 :param set titles:
154 :py:attr:`titles` wrapped with :py:class:`SetManager`.
155 :param set first_name_titles:
156 :py:attr:`~titles.FIRST_NAME_TITLES` wrapped with :py:class:`SetManager`.
157 :param set suffix_acronyms:
158 :py:attr:`~suffixes.SUFFIX_ACRONYMS` wrapped with :py:class:`SetManager`.
159 :param set suffix_not_acronyms:
160 :py:attr:`~suffixes.SUFFIX_NOT_ACRONYMS` wrapped with :py:class:`SetManager`.
161 :param set conjunctions:
162 :py:attr:`conjunctions` wrapped with :py:class:`SetManager`.
163 :type capitalization_exceptions: tuple or dict
164 :param capitalization_exceptions:
165 :py:attr:`~capitalization.CAPITALIZATION_EXCEPTIONS` wrapped with :py:class:`TupleManager`.
166 :type regexes: tuple or dict
167 :param regexes:
168 :py:attr:`regexes` wrapped with :py:class:`TupleManager`.
169 """
171 string_format = "{title} {first} {middle} {last} {suffix} ({nickname})"
172 """
173 The default string format use for all new `HumanName` instances.
174 """
176 initials_format = "{first} {middle} {last}"
177 """
178 The default initials format used for all new `HumanName` instances.
179 """
181 initials_delimiter = "."
182 """
183 The default initials delimiter used for all new `HumanName` instances.
184 Will be used to add a delimiter between each initial.
185 """
187 empty_attribute_default = ''
188 """
189 Default return value for empty attributes.
191 .. doctest::
193 >>> from nameparser.config import CONSTANTS
194 >>> CONSTANTS.empty_attribute_default = None
195 >>> name = HumanName("John Doe")
196 >>> name.title
197 None
198 >>>name.first
199 'John'
201 """
203 capitalize_name = False
204 """
205 If set, applies :py:meth:`~nameparser.parser.HumanName.capitalize` to
206 :py:class:`~nameparser.parser.HumanName` instance.
208 .. doctest::
210 >>> from nameparser.config import CONSTANTS
211 >>> CONSTANTS.capitalize_name = True
212 >>> name = HumanName("bob v. de la macdole-eisenhower phd")
213 >>> str(name)
214 'Bob V. de la MacDole-Eisenhower Ph.D.'
216 """
218 force_mixed_case_capitalization = False
219 """
220 If set, forces the capitalization of mixed case strings when
221 :py:meth:`~nameparser.parser.HumanName.capitalize` is called.
223 .. doctest::
225 >>> from nameparser.config import CONSTANTS
226 >>> CONSTANTS.force_mixed_case_capitalization = True
227 >>> name = HumanName('Shirley Maclaine')
228 >>> name.capitalize()
229 >>> str(name)
230 'Shirley MacLaine'
232 """
234 def __init__(self,
235 prefixes=PREFIXES,
236 suffix_acronyms=SUFFIX_ACRONYMS,
237 suffix_not_acronyms=SUFFIX_NOT_ACRONYMS,
238 titles=TITLES,
239 first_name_titles=FIRST_NAME_TITLES,
240 conjunctions=CONJUNCTIONS,
241 capitalization_exceptions=CAPITALIZATION_EXCEPTIONS,
242 regexes=REGEXES
243 ):
244 self.prefixes = SetManager(prefixes)
245 self.suffix_acronyms = SetManager(suffix_acronyms)
246 self.suffix_not_acronyms = SetManager(suffix_not_acronyms)
247 self.titles = SetManager(titles)
248 self.first_name_titles = SetManager(first_name_titles)
249 self.conjunctions = SetManager(conjunctions)
250 self.capitalization_exceptions = TupleManager(capitalization_exceptions)
251 self.regexes = TupleManager(regexes)
252 self._pst = None
254 @property
255 def suffixes_prefixes_titles(self):
256 if not self._pst:
257 self._pst = self.prefixes | self.suffix_acronyms | self.suffix_not_acronyms | self.titles
258 return self._pst
260 def __repr__(self):
261 return "<Constants() instance>"
263 def __setstate__(self, state):
264 self.__init__(state)
266 def __getstate__(self):
267 attrs = [x for x in dir(self) if not x.startswith('_')]
268 return dict([(a, getattr(self, a)) for a in attrs])
271#: A module-level instance of the :py:class:`Constants()` class.
272#: Provides a common instance for the module to share
273#: to easily adjust configuration for the entire module.
274#: See `Customizing the Parser with Your Own Configuration <customize.html>`_.
275CONSTANTS = Constants()