Skip to content

Commit 3680ebe

Browse files
bpo-44712: Replace "type(literal)" with corresponding builtin types (GH-27294)
I suppose it is a remnants of very old code written when str, int, list, dict, etc were functions and not classes.
1 parent c826867 commit 3680ebe

File tree

19 files changed

+41
-39
lines changed

19 files changed

+41
-39
lines changed

Lib/cgitb.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def lookup(name, frame, locals):
7474
return 'global', frame.f_globals[name]
7575
if '__builtins__' in frame.f_globals:
7676
builtins = frame.f_globals['__builtins__']
77-
if type(builtins) is type({}):
77+
if isinstance(builtins, dict):
7878
if name in builtins:
7979
return 'builtin', builtins[name]
8080
else:

Lib/csv.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,7 @@ def has_header(self, sample):
428428
# on whether it's a header
429429
hasHeader = 0
430430
for col, colType in columnTypes.items():
431-
if type(colType) == type(0): # it's a length
431+
if isinstance(colType, int): # it's a length
432432
if len(header[col]) != colType:
433433
hasHeader += 1
434434
else:

Lib/curses/ascii.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
]
4747

4848
def _ctoi(c):
49-
if type(c) == type(""):
49+
if isinstance(c, str):
5050
return ord(c)
5151
else:
5252
return c
@@ -69,19 +69,19 @@ def isctrl(c): return 0 <= _ctoi(c) < 32
6969
def ismeta(c): return _ctoi(c) > 127
7070

7171
def ascii(c):
72-
if type(c) == type(""):
72+
if isinstance(c, str):
7373
return chr(_ctoi(c) & 0x7f)
7474
else:
7575
return _ctoi(c) & 0x7f
7676

7777
def ctrl(c):
78-
if type(c) == type(""):
78+
if isinstance(c, str):
7979
return chr(_ctoi(c) & 0x1f)
8080
else:
8181
return _ctoi(c) & 0x1f
8282

8383
def alt(c):
84-
if type(c) == type(""):
84+
if isinstance(c, str):
8585
return chr(_ctoi(c) | 0x80)
8686
else:
8787
return _ctoi(c) | 0x80

Lib/distutils/command/register.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ def post_to_server(self, data, auth=None):
260260
body = io.StringIO()
261261
for key, value in data.items():
262262
# handle multiple entries for the same name
263-
if type(value) not in (type([]), type( () )):
263+
if not isinstance(value, (list, tuple)):
264264
value = [value]
265265
for value in value:
266266
value = str(value)

Lib/ftplib.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -561,7 +561,7 @@ def dir(self, *args):
561561
LIST command. (This *should* only be used for a pathname.)'''
562562
cmd = 'LIST'
563563
func = None
564-
if args[-1:] and type(args[-1]) != type(''):
564+
if args[-1:] and not isinstance(args[-1], str):
565565
args, func = args[:-1], args[-1]
566566
for arg in args:
567567
if arg:

Lib/getopt.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def getopt(args, shortopts, longopts = []):
8181
"""
8282

8383
opts = []
84-
if type(longopts) == type(""):
84+
if isinstance(longopts, str):
8585
longopts = [longopts]
8686
else:
8787
longopts = list(longopts)

Lib/idlelib/browser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def transform_children(child_dict, modname=None):
4343
# If obj.name != key, it has already been suffixed.
4444
supers = []
4545
for sup in obj.super:
46-
if type(sup) is type(''):
46+
if isinstance(sup, str):
4747
sname = sup
4848
else:
4949
sname = sup.name

Lib/lib2to3/pgen2/token.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@
7272

7373
tok_name = {}
7474
for _name, _value in list(globals().items()):
75-
if type(_value) is type(0):
75+
if isinstance(_value, int):
7676
tok_name[_value] = _name
7777

7878

Lib/plistlib.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ def handle_data(self, data):
199199

200200
def add_object(self, value):
201201
if self.current_key is not None:
202-
if not isinstance(self.stack[-1], type({})):
202+
if not isinstance(self.stack[-1], dict):
203203
raise ValueError("unexpected element at line %d" %
204204
self.parser.CurrentLineNumber)
205205
self.stack[-1][self.current_key] = value
@@ -208,7 +208,7 @@ def add_object(self, value):
208208
# this is the root object
209209
self.root = value
210210
else:
211-
if not isinstance(self.stack[-1], type([])):
211+
if not isinstance(self.stack[-1], list):
212212
raise ValueError("unexpected element at line %d" %
213213
self.parser.CurrentLineNumber)
214214
self.stack[-1].append(value)
@@ -232,7 +232,7 @@ def end_dict(self):
232232
self.stack.pop()
233233

234234
def end_key(self):
235-
if self.current_key or not isinstance(self.stack[-1], type({})):
235+
if self.current_key or not isinstance(self.stack[-1], dict):
236236
raise ValueError("unexpected key at line %d" %
237237
self.parser.CurrentLineNumber)
238238
self.current_key = self.get_data()

Lib/pty.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ def _copy(master_fd, master_read=_read, stdin_read=_read):
162162

163163
def spawn(argv, master_read=_read, stdin_read=_read):
164164
"""Create a spawned process."""
165-
if type(argv) == type(''):
165+
if isinstance(argv, str):
166166
argv = (argv,)
167167
sys.audit('pty.spawn', argv)
168168

Lib/pydoc.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -727,7 +727,7 @@ def formattree(self, tree, modname, parent=None):
727727
"""Produce HTML for a class tree as given by inspect.getclasstree()."""
728728
result = ''
729729
for entry in tree:
730-
if type(entry) is type(()):
730+
if isinstance(entry, tuple):
731731
c, bases = entry
732732
result = result + '<dt class="heading-text">'
733733
result = result + self.classlink(c, modname)
@@ -737,7 +737,7 @@ def formattree(self, tree, modname, parent=None):
737737
parents.append(self.classlink(base, modname))
738738
result = result + '(' + ', '.join(parents) + ')'
739739
result = result + '\n</dt>'
740-
elif type(entry) is type([]):
740+
elif isinstance(entry, list):
741741
result = result + '<dd>\n%s</dd>\n' % self.formattree(
742742
entry, modname, c)
743743
return '<dl>\n%s</dl>\n' % result
@@ -1190,14 +1190,14 @@ def formattree(self, tree, modname, parent=None, prefix=''):
11901190
"""Render in text a class tree as returned by inspect.getclasstree()."""
11911191
result = ''
11921192
for entry in tree:
1193-
if type(entry) is type(()):
1193+
if isinstance(entry, tuple):
11941194
c, bases = entry
11951195
result = result + prefix + classname(c, modname)
11961196
if bases and bases != (parent,):
11971197
parents = (classname(c, modname) for c in bases)
11981198
result = result + '(%s)' % ', '.join(parents)
11991199
result = result + '\n'
1200-
elif type(entry) is type([]):
1200+
elif isinstance(entry, list):
12011201
result = result + self.formattree(
12021202
entry, modname, c, prefix + ' ')
12031203
return result
@@ -2044,7 +2044,7 @@ def getline(self, prompt):
20442044
return self.input.readline()
20452045

20462046
def help(self, request):
2047-
if type(request) is type(''):
2047+
if isinstance(request, str):
20482048
request = request.strip()
20492049
if request == 'keywords': self.listkeywords()
20502050
elif request == 'symbols': self.listsymbols()
@@ -2129,7 +2129,7 @@ def showtopic(self, topic, more_xrefs=''):
21292129
if not target:
21302130
self.output.write('no documentation found for %s\n' % repr(topic))
21312131
return
2132-
if type(target) is type(''):
2132+
if isinstance(target, str):
21332133
return self.showtopic(target, more_xrefs)
21342134

21352135
label, xrefs = target

Lib/sunau.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def _write_u32(file, x):
160160
class Au_read:
161161

162162
def __init__(self, f):
163-
if type(f) == type(''):
163+
if isinstance(f, str):
164164
import builtins
165165
f = builtins.open(f, 'rb')
166166
self._opened = True
@@ -312,7 +312,7 @@ def close(self):
312312
class Au_write:
313313

314314
def __init__(self, f):
315-
if type(f) == type(''):
315+
if isinstance(f, str):
316316
import builtins
317317
f = builtins.open(f, 'wb')
318318
self._opened = True

Lib/test/test_copyreg.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
class C:
77
pass
88

9+
def pickle_C(c):
10+
return C, ()
11+
912

1013
class WithoutSlots(object):
1114
pass
@@ -32,16 +35,15 @@ class WithInherited(WithSingleString):
3235
class CopyRegTestCase(unittest.TestCase):
3336

3437
def test_class(self):
35-
self.assertRaises(TypeError, copyreg.pickle,
36-
C, None, None)
38+
copyreg.pickle(C, pickle_C)
3739

3840
def test_noncallable_reduce(self):
3941
self.assertRaises(TypeError, copyreg.pickle,
40-
type(1), "not a callable")
42+
C, "not a callable")
4143

4244
def test_noncallable_constructor(self):
4345
self.assertRaises(TypeError, copyreg.pickle,
44-
type(1), int, "not a callable")
46+
C, pickle_C, "not a callable")
4547

4648
def test_bool(self):
4749
import copy

Lib/test/test_descr.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,7 @@ def __init__(self_local, *a, **kw):
426426
def __getitem__(self, key):
427427
return self.get(key, 0)
428428
def __setitem__(self_local, key, value):
429-
self.assertIsInstance(key, type(0))
429+
self.assertIsInstance(key, int)
430430
dict.__setitem__(self_local, key, value)
431431
def setstate(self, state):
432432
self.state = state
@@ -871,7 +871,7 @@ def setstate(self, state):
871871
self.assertEqual(a.getstate(), 10)
872872
class D(dict, C):
873873
def __init__(self):
874-
type({}).__init__(self)
874+
dict.__init__(self)
875875
C.__init__(self)
876876
d = D()
877877
self.assertEqual(list(d.keys()), [])
@@ -3288,7 +3288,7 @@ class Int(int): __slots__ = []
32883288
cant(True, int)
32893289
cant(2, bool)
32903290
o = object()
3291-
cant(o, type(1))
3291+
cant(o, int)
32923292
cant(o, type(None))
32933293
del o
32943294
class G(object):

Lib/test/test_pprint.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ def test_knotted(self):
203203
def test_unreadable(self):
204204
# Not recursive but not readable anyway
205205
pp = pprint.PrettyPrinter()
206-
for unreadable in type(3), pprint, pprint.isrecursive:
206+
for unreadable in object(), int, pprint, pprint.isrecursive:
207207
# module-level convenience functions
208208
self.assertFalse(pprint.isrecursive(unreadable),
209209
"expected not isrecursive for %r" % (unreadable,))

Lib/test/test_timeout.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,10 @@ def testFloatReturnValue(self):
5050
def testReturnType(self):
5151
# Test return type of gettimeout()
5252
self.sock.settimeout(1)
53-
self.assertEqual(type(self.sock.gettimeout()), type(1.0))
53+
self.assertIs(type(self.sock.gettimeout()), float)
5454

5555
self.sock.settimeout(3.9)
56-
self.assertEqual(type(self.sock.gettimeout()), type(1.0))
56+
self.assertIs(type(self.sock.gettimeout()), float)
5757

5858
def testTypeCheck(self):
5959
# Test type checking by settimeout()

Lib/xmlrpc/client.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -850,9 +850,9 @@ def __init__(self, results):
850850

851851
def __getitem__(self, i):
852852
item = self.results[i]
853-
if type(item) == type({}):
853+
if isinstance(item, dict):
854854
raise Fault(item['faultCode'], item['faultString'])
855-
elif type(item) == type([]):
855+
elif isinstance(item, list):
856856
return item[0]
857857
else:
858858
raise ValueError("unexpected type in multicall result")

Mac/BuildScript/build-installer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1351,7 +1351,7 @@ def buildPython():
13511351
build_time_vars = l_dict['build_time_vars']
13521352
vars = {}
13531353
for k, v in build_time_vars.items():
1354-
if type(v) == type(''):
1354+
if isinstance(v, str):
13551355
for p in (include_path, lib_path):
13561356
v = v.replace(' ' + p, '')
13571357
v = v.replace(p + ' ', '')

Tools/scripts/mailerdaemon.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def get_errors(self):
7070
# compile the re's in the list and store them in-place.
7171
for i in range(len(emparse_list_list)):
7272
x = emparse_list_list[i]
73-
if type(x) is type(''):
73+
if isinstance(x, str):
7474
x = re.compile(x, re.MULTILINE)
7575
else:
7676
xl = []
@@ -105,7 +105,7 @@ def emparse_list(fp, sub):
105105
emails = []
106106
reason = None
107107
for regexp in emparse_list_list:
108-
if type(regexp) is type(()):
108+
if isinstance(regexp, tuple):
109109
res = regexp[0].search(data, 0, from_index)
110110
if res is not None:
111111
try:
@@ -134,7 +134,7 @@ def emparse_list(fp, sub):
134134
if reason[:15] == 'returned mail: ':
135135
reason = reason[15:]
136136
for regexp in emparse_list_reason:
137-
if type(regexp) is type(''):
137+
if isinstance(regexp, str):
138138
for i in range(len(emails)-1,-1,-1):
139139
email = emails[i]
140140
exp = re.compile(re.escape(email).join(regexp.split('<>')), re.MULTILINE)

0 commit comments

Comments
 (0)