Skip to content

Commit b7f64d3

Browse files
committed
Remove obsolete Python 2 compatibility code
The changes are mostly related to unicode and conditional imports.
1 parent a94b4a7 commit b7f64d3

12 files changed

Lines changed: 70 additions & 144 deletions

File tree

docs/conf.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
#
32
# Nameparser documentation build configuration file, created by
43
# sphinx-quickstart on Fri May 16 01:29:58 2014.
@@ -49,8 +48,8 @@
4948
master_doc = 'index'
5049

5150
# General information about the project.
52-
project = u'Nameparser'
53-
copyright = u'{:%Y}, Derek Gulbranson'.format(date.today())
51+
project = 'Nameparser'
52+
copyright = '{:%Y}, Derek Gulbranson'.format(date.today())
5453

5554
# The version info for the project you're documenting, acts as replacement for
5655
# |version| and |release|, also used in various other places throughout the
@@ -223,8 +222,8 @@
223222
# (source start file, target name, title,
224223
# author, documentclass [howto, manual, or own class]).
225224
latex_documents = [
226-
('index', 'Nameparser.tex', u'Nameparser Documentation',
227-
u'Derek Gulbranson', 'manual'),
225+
('index', 'Nameparser.tex', 'Nameparser Documentation',
226+
'Derek Gulbranson', 'manual'),
228227
]
229228

230229
# The name of an image file (relative to this directory) to place at the top of
@@ -253,8 +252,8 @@
253252
# One entry per manual page. List of tuples
254253
# (source start file, name, description, authors, manual section).
255254
man_pages = [
256-
('index', 'nameparser', u'Nameparser Documentation',
257-
[u'Derek Gulbranson'], 1)
255+
('index', 'nameparser', 'Nameparser Documentation',
256+
['Derek Gulbranson'], 1)
258257
]
259258

260259
# If true, show URL addresses after external links.
@@ -267,8 +266,8 @@
267266
# (source start file, target name, title, author,
268267
# dir menu entry, description, category)
269268
texinfo_documents = [
270-
('index', 'Nameparser', u'Nameparser Documentation',
271-
u'Derek Gulbranson', 'Nameparser', 'A simple python modules for parsing human names into components.',
269+
('index', 'Nameparser', 'Nameparser Documentation',
270+
'Derek Gulbranson', 'Nameparser', 'A simple python modules for parsing human names into components.',
272271
'Miscellaneous'),
273272
]
274273

nameparser/config/__init__.py

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
The :py:mod:`nameparser.config` module manages the configuration of the
43
nameparser.
@@ -28,15 +27,9 @@
2827
``hn.C`` will be a reference to the module config, possibly yielding
2928
unexpected results. See `Customizing the Parser <customize.html>`_.
3029
"""
31-
from __future__ import unicode_literals
3230
import sys
33-
try:
34-
# Python 3.3+
35-
from collections.abc import Set
36-
except ImportError:
37-
from collections import Set
31+
from collections.abc import Set
3832

39-
from nameparser.util import binary_type
4033
from nameparser.util import lc
4134
from nameparser.config.prefixes import PREFIXES
4235
from nameparser.config.capitalization import CAPITALIZATION_EXCEPTIONS
@@ -102,7 +95,7 @@ def add_with_encoding(self, s, encoding=None):
10295
if sys.stdin:
10396
stdin_encoding = sys.stdin.encoding
10497
encoding = encoding or stdin_encoding or DEFAULT_ENCODING
105-
if type(s) == binary_type:
98+
if isinstance(s, bytes):
10699
s = s.decode(encoding)
107100
self.elements.add(lc(s))
108101

@@ -144,7 +137,7 @@ def __reduce__(self):
144137
return (TupleManager, (), self.__getstate__())
145138

146139

147-
class Constants(object):
140+
class Constants:
148141
"""
149142
An instance of this class hold all of the configuration constants for the parser.
150143
Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
# -*- coding: utf-8 -*-
2-
from __future__ import unicode_literals
3-
41
CAPITALIZATION_EXCEPTIONS = (
52
('ii', 'II'),
63
('iii', 'III'),
@@ -10,4 +7,4 @@
107
)
118
"""
129
Any pieces that are not capitalized by capitalizing the first letter.
13-
"""
10+
"""

nameparser/config/conjunctions.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
# -*- coding: utf-8 -*-
2-
from __future__ import unicode_literals
3-
41
CONJUNCTIONS = set([
52
'&',
63
'and',
@@ -15,4 +12,4 @@
1512
Pieces that should join to their neighboring pieces, e.g. "and", "y" and "&".
1613
"of" and "the" are also include to facilitate joining multiple titles,
1714
e.g. "President of the United States".
18-
"""
15+
"""

nameparser/config/prefixes.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
# -*- coding: utf-8 -*-
2-
from __future__ import unicode_literals
3-
41
#: Name pieces that appear before a last name. Prefixes join to the piece
52
#: that follows them to make one new piece. They can be chained together, e.g
63
#: "von der" and "de la". Because they only appear in middle or last names,

nameparser/config/regexes.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# -*- coding: utf-8 -*-
2-
from __future__ import unicode_literals
31
import re
42

53
# emoji regex from https://stackoverflow.com/questions/26568722/remove-unicode-emoji-using-re-in-python

nameparser/config/suffixes.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
# -*- coding: utf-8 -*-
2-
from __future__ import unicode_literals
3-
41
SUFFIX_NOT_ACRONYMS = set([
52
'dr',
63
'esq',

nameparser/config/titles.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
# -*- coding: utf-8 -*-
2-
from __future__ import unicode_literals
3-
41
FIRST_NAME_TITLES = set([
52
'aunt',
63
'auntie',

nameparser/parser.py

Lines changed: 23 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,8 @@
1-
# -*- coding: utf-8 -*-
2-
from __future__ import unicode_literals
3-
41
import sys
52
import re
63
from operator import itemgetter
74
from itertools import groupby
85

9-
from nameparser.util import u
10-
from nameparser.util import text_types, binary_type
116
from nameparser.util import lc
127
from nameparser.util import log
138
from nameparser.config import CONSTANTS
@@ -30,7 +25,7 @@ def group_contiguous_integers(data):
3025
return ranges
3126

3227

33-
class HumanName(object):
28+
class HumanName:
3429
"""
3530
Parse a person's name into individual components.
3631
@@ -123,10 +118,10 @@ def __eq__(self, other):
123118
HumanName instances are equal to other objects whose
124119
lower case unicode representation is the same.
125120
"""
126-
return (u(self)).lower() == (u(other)).lower()
121+
return str(self).lower() == str(other).lower()
127122

128123
def __ne__(self, other):
129-
return not (u(self)).lower() == (u(other)).lower()
124+
return str(self).lower() != str(other).lower()
130125

131126
def __getitem__(self, key):
132127
if isinstance(key, slice):
@@ -152,7 +147,7 @@ def __next__(self):
152147
self._count = c + 1
153148
return getattr(self, self._members[c]) or next(self)
154149

155-
def __unicode__(self):
150+
def __str__(self):
156151
if self.string_format:
157152
# string_format = "{title} {first} {middle} {last} {suffix} ({nickname})"
158153
_s = self.string_format.format(**self.as_dict())
@@ -164,27 +159,19 @@ def __unicode__(self):
164159
def __hash__(self):
165160
return hash(str(self))
166161

167-
def __str__(self):
168-
if sys.version_info[0] >= 3:
169-
return self.__unicode__()
170-
return self.__unicode__().encode(self.encoding)
171-
172162
def __repr__(self):
173163
if self.unparsable:
174-
_string = "<%(class)s : [ Unparsable ] >" % {'class': self.__class__.__name__, }
175-
else:
176-
_string = "<%(class)s : [\n\ttitle: %(title)r \n\tfirst: %(first)r \n\tmiddle: %(middle)r \n\tlast: %(last)r \n\tsuffix: %(suffix)r\n\tnickname: %(nickname)r\n]>" % {
177-
'class': self.__class__.__name__,
178-
'title': self.title or '',
179-
'first': self.first or '',
180-
'middle': self.middle or '',
181-
'last': self.last or '',
182-
'suffix': self.suffix or '',
183-
'nickname': self.nickname or '',
184-
}
185-
if sys.version_info[0] >= 3:
186-
return _string
187-
return _string.encode(self.encoding)
164+
return "<%(class)s : [ Unparsable ] >" % {'class': self.__class__.__name__, }
165+
166+
return "<%(class)s : [\n\ttitle: %(title)r \n\tfirst: %(first)r \n\tmiddle: %(middle)r \n\tlast: %(last)r \n\tsuffix: %(suffix)r\n\tnickname: %(nickname)r\n]>" % {
167+
'class': self.__class__.__name__,
168+
'title': self.title or '',
169+
'first': self.first or '',
170+
'middle': self.middle or '',
171+
'last': self.last or '',
172+
'suffix': self.suffix or '',
173+
'nickname': self.nickname or '',
174+
}
188175

189176
def as_dict(self, include_empty=True):
190177
"""
@@ -361,14 +348,14 @@ def surnames(self):
361348
def _set_list(self, attr, value):
362349
if isinstance(value, list):
363350
val = value
364-
elif isinstance(value, text_types):
351+
elif isinstance(value, str | bytes):
365352
val = [value]
366353
elif value is None:
367354
val = []
368355
else:
369356
raise TypeError(
370357
"Can only assign strings, lists or None to name attributes."
371-
" Got {0}".format(type(value)))
358+
f" Got {0}".format(type(value)))
372359
setattr(self, attr+"_list", self.parse_pieces(val))
373360

374361
@title.setter
@@ -481,7 +468,7 @@ def full_name(self):
481468
def full_name(self, value):
482469
self.original = value
483470
self._full_name = value
484-
if isinstance(value, binary_type):
471+
if isinstance(value, bytes):
485472
self._full_name = value.decode(self.encoding)
486473
self.parse_full_name()
487474

@@ -657,7 +644,7 @@ def parse_full_name(self):
657644

658645
self.suffix_list += parts[1:]
659646
pieces = self.parse_pieces(parts[0].split(' '))
660-
log.debug("pieces: %s", u(pieces))
647+
log.debug("pieces: %s", str(pieces))
661648
for i, piece in enumerate(pieces):
662649
try:
663650
nxt = pieces[i + 1]
@@ -686,7 +673,7 @@ def parse_full_name(self):
686673
# last [suffix], title first middles[,] suffix [,suffix]
687674
# parts[0], parts[1], parts[2:...]
688675

689-
log.debug("post-comma pieces: %s", u(post_comma_pieces))
676+
log.debug("post-comma pieces: %s", str(post_comma_pieces))
690677

691678
# lastname part may have suffixes in it
692679
lastname_pieces = self.parse_pieces(parts[0].split(' '), 1)
@@ -747,9 +734,9 @@ def parse_pieces(self, parts, additional_parts_count=0):
747734

748735
output = []
749736
for part in parts:
750-
if not isinstance(part, text_types):
737+
if not isinstance(part, str | bytes):
751738
raise TypeError("Name parts must be strings. "
752-
"Got {0}".format(type(part)))
739+
f"Got {type(part)}")
753740
output += [x.strip(' ,') for x in part.split(' ')]
754741

755742
# If part contains periods, check if it's multiple titles or suffixes
@@ -981,7 +968,7 @@ def capitalize(self, force=None):
981968
'Shirley MacLaine'
982969
983970
"""
984-
name = u(self)
971+
name = str(self)
985972
force = self.C.force_mixed_case_capitalization \
986973
if force is None else force
987974

nameparser/util.py

Lines changed: 2 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,11 @@
11
import logging
22

3-
# http://code.google.com/p/python-nameparser/issues/detail?id=10
3+
44
log = logging.getLogger('HumanName')
5-
try:
6-
log.addHandler(logging.NullHandler())
7-
except AttributeError:
8-
class NullHandler(logging.Handler):
9-
def emit(self, record):
10-
pass
11-
log.addHandler(NullHandler())
5+
log.addHandler(logging.NullHandler())
126
log.setLevel(logging.ERROR)
137

148

15-
import sys
16-
if sys.version_info[0] < 3:
17-
18-
text_type = unicode
19-
binary_type = str
20-
21-
def u(x, encoding=None):
22-
if encoding:
23-
return unicode(x, encoding)
24-
else:
25-
return unicode(x)
26-
27-
else:
28-
text_type = str
29-
binary_type = bytes
30-
31-
def u(x, encoding=None):
32-
return text_type(x)
33-
34-
text_types = (text_type, binary_type)
359
def lc(value):
3610
"""Lower case and remove any periods to normalize for comparison."""
3711
if not value:

0 commit comments

Comments
 (0)