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

Skip to content

Commit 1f21eaa

Browse files
bpo-15999: Clean up of handling boolean arguments. (GH-15610)
* Use the 'p' format unit instead of manually called PyObject_IsTrue(). * Pass boolean value instead 0/1 integers to functions that needs boolean. * Convert some arguments to boolean only once.
1 parent 5eca7f3 commit 1f21eaa

21 files changed

+69
-78
lines changed

Lib/_pyio.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2295,7 +2295,7 @@ def _read_chunk(self):
22952295
return not eof
22962296

22972297
def _pack_cookie(self, position, dec_flags=0,
2298-
bytes_to_feed=0, need_eof=0, chars_to_skip=0):
2298+
bytes_to_feed=0, need_eof=False, chars_to_skip=0):
22992299
# The meaning of a tell() cookie is: seek to position, set the
23002300
# decoder flags to dec_flags, read bytes_to_feed bytes, feed them
23012301
# into the decoder with need_eof as the EOF flag, then skip
@@ -2309,7 +2309,7 @@ def _unpack_cookie(self, bigint):
23092309
rest, dec_flags = divmod(rest, 1<<64)
23102310
rest, bytes_to_feed = divmod(rest, 1<<64)
23112311
need_eof, chars_to_skip = divmod(rest, 1<<64)
2312-
return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
2312+
return position, dec_flags, bytes_to_feed, bool(need_eof), chars_to_skip
23132313

23142314
def tell(self):
23152315
if not self._seekable:
@@ -2383,7 +2383,7 @@ def tell(self):
23832383
# (a point where the decoder has nothing buffered, so seek()
23842384
# can safely start from there and advance to this location).
23852385
bytes_fed = 0
2386-
need_eof = 0
2386+
need_eof = False
23872387
# Chars decoded since `start_pos`
23882388
chars_decoded = 0
23892389
for i in range(skip_bytes, len(next_input)):
@@ -2400,7 +2400,7 @@ def tell(self):
24002400
else:
24012401
# We didn't get enough decoded data; signal EOF to get more.
24022402
chars_decoded += len(decoder.decode(b'', final=True))
2403-
need_eof = 1
2403+
need_eof = True
24042404
if chars_decoded < chars_to_skip:
24052405
raise OSError("can't reconstruct logical file position")
24062406

Lib/codeop.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ def __init__(self):
130130
self.flags = PyCF_DONT_IMPLY_DEDENT
131131

132132
def __call__(self, source, filename, symbol):
133-
codeob = compile(source, filename, symbol, self.flags, 1)
133+
codeob = compile(source, filename, symbol, self.flags, True)
134134
for feature in _features:
135135
if codeob.co_flags & feature.compiler_flag:
136136
self.flags |= feature.compiler_flag

Lib/doctest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1326,7 +1326,7 @@ def __run(self, test, compileflags, out):
13261326
try:
13271327
# Don't blink! This is where the user's code gets run.
13281328
exec(compile(example.source, filename, "single",
1329-
compileflags, 1), test.globs)
1329+
compileflags, True), test.globs)
13301330
self.debugger.set_continue() # ==== Example Finished ====
13311331
exception = None
13321332
except KeyboardInterrupt:

Lib/quopri.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -204,11 +204,11 @@ def main():
204204
print("-t: quote tabs")
205205
print("-d: decode; default encode")
206206
sys.exit(2)
207-
deco = 0
208-
tabs = 0
207+
deco = False
208+
tabs = False
209209
for o, a in opts:
210-
if o == '-t': tabs = 1
211-
if o == '-d': deco = 1
210+
if o == '-t': tabs = True
211+
if o == '-d': deco = True
212212
if tabs and deco:
213213
sys.stdout = sys.stderr
214214
print("-t and -d are mutually exclusive")

Lib/test/datetimetester.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6160,7 +6160,7 @@ class TZInfoSubclass(tzinfo):
61606160
def test_date_from_date(self):
61616161
exp_date = date(1993, 8, 26)
61626162

6163-
for macro in [0, 1]:
6163+
for macro in False, True:
61646164
with self.subTest(macro=macro):
61656165
c_api_date = _testcapi.get_date_fromdate(
61666166
macro,
@@ -6173,7 +6173,7 @@ def test_date_from_date(self):
61736173
def test_datetime_from_dateandtime(self):
61746174
exp_date = datetime(1993, 8, 26, 22, 12, 55, 99999)
61756175

6176-
for macro in [0, 1]:
6176+
for macro in False, True:
61776177
with self.subTest(macro=macro):
61786178
c_api_date = _testcapi.get_datetime_fromdateandtime(
61796179
macro,
@@ -6191,7 +6191,7 @@ def test_datetime_from_dateandtimeandfold(self):
61916191
exp_date = datetime(1993, 8, 26, 22, 12, 55, 99999)
61926192

61936193
for fold in [0, 1]:
6194-
for macro in [0, 1]:
6194+
for macro in False, True:
61956195
with self.subTest(macro=macro, fold=fold):
61966196
c_api_date = _testcapi.get_datetime_fromdateandtimeandfold(
61976197
macro,
@@ -6210,7 +6210,7 @@ def test_datetime_from_dateandtimeandfold(self):
62106210
def test_time_from_time(self):
62116211
exp_time = time(22, 12, 55, 99999)
62126212

6213-
for macro in [0, 1]:
6213+
for macro in False, True:
62146214
with self.subTest(macro=macro):
62156215
c_api_time = _testcapi.get_time_fromtime(
62166216
macro,
@@ -6225,7 +6225,7 @@ def test_time_from_timeandfold(self):
62256225
exp_time = time(22, 12, 55, 99999)
62266226

62276227
for fold in [0, 1]:
6228-
for macro in [0, 1]:
6228+
for macro in False, True:
62296229
with self.subTest(macro=macro, fold=fold):
62306230
c_api_time = _testcapi.get_time_fromtimeandfold(
62316231
macro,
@@ -6241,7 +6241,7 @@ def test_time_from_timeandfold(self):
62416241
def test_delta_from_dsu(self):
62426242
exp_delta = timedelta(26, 55, 99999)
62436243

6244-
for macro in [0, 1]:
6244+
for macro in False, True:
62456245
with self.subTest(macro=macro):
62466246
c_api_delta = _testcapi.get_delta_fromdsu(
62476247
macro,
@@ -6254,7 +6254,7 @@ def test_delta_from_dsu(self):
62546254
def test_date_from_timestamp(self):
62556255
ts = datetime(1995, 4, 12).timestamp()
62566256

6257-
for macro in [0, 1]:
6257+
for macro in False, True:
62586258
with self.subTest(macro=macro):
62596259
d = _testcapi.get_date_fromtimestamp(int(ts), macro)
62606260

@@ -6272,7 +6272,7 @@ def test_datetime_from_timestamp(self):
62726272

62736273
from_timestamp = _testcapi.get_datetime_fromtimestamp
62746274
for case in cases:
6275-
for macro in [0, 1]:
6275+
for macro in False, True:
62766276
with self.subTest(case=case, macro=macro):
62776277
dtup, tzinfo, usetz = case
62786278
dt_orig = datetime(*dtup, tzinfo=tzinfo)

Lib/test/lock_tests.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ def f():
182182
def test_timeout(self):
183183
lock = self.locktype()
184184
# Can't set timeout if not blocking
185-
self.assertRaises(ValueError, lock.acquire, 0, 1)
185+
self.assertRaises(ValueError, lock.acquire, False, 1)
186186
# Invalid timeout values
187187
self.assertRaises(ValueError, lock.acquire, timeout=-100)
188188
self.assertRaises(OverflowError, lock.acquire, timeout=1e100)

Lib/test/test_builtin.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -320,8 +320,8 @@ def test_compile(self):
320320
bom = b'\xef\xbb\xbf'
321321
compile(bom + b'print(1)\n', '', 'exec')
322322
compile(source='pass', filename='?', mode='exec')
323-
compile(dont_inherit=0, filename='tmp', source='0', mode='eval')
324-
compile('pass', '?', dont_inherit=1, mode='exec')
323+
compile(dont_inherit=False, filename='tmp', source='0', mode='eval')
324+
compile('pass', '?', dont_inherit=True, mode='exec')
325325
compile(memoryview(b"text"), "name", "exec")
326326
self.assertRaises(TypeError, compile)
327327
self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode')
@@ -1853,7 +1853,7 @@ def test_basic(self):
18531853
self.assertEqual(data, sorted(copy, key=lambda x: -x))
18541854
self.assertNotEqual(data, copy)
18551855
random.shuffle(copy)
1856-
self.assertEqual(data, sorted(copy, reverse=1))
1856+
self.assertEqual(data, sorted(copy, reverse=True))
18571857
self.assertNotEqual(data, copy)
18581858

18591859
def test_bad_arguments(self):

Lib/test/test_ioctl.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def _check_ioctl_mutate_len(self, nbytes=None):
4848
else:
4949
buf.append(fill)
5050
with open("/dev/tty", "rb") as tty:
51-
r = fcntl.ioctl(tty, termios.TIOCGPGRP, buf, 1)
51+
r = fcntl.ioctl(tty, termios.TIOCGPGRP, buf, True)
5252
rpgrp = buf[0]
5353
self.assertEqual(r, 0)
5454
self.assertIn(rpgrp, ids)

Lib/test/test_ordered_dict.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -407,9 +407,9 @@ def test_move_to_end(self):
407407
self.assertEqual(list(od), list('abcde'))
408408
od.move_to_end('c')
409409
self.assertEqual(list(od), list('abdec'))
410-
od.move_to_end('c', 0)
410+
od.move_to_end('c', False)
411411
self.assertEqual(list(od), list('cabde'))
412-
od.move_to_end('c', 0)
412+
od.move_to_end('c', False)
413413
self.assertEqual(list(od), list('cabde'))
414414
od.move_to_end('e')
415415
self.assertEqual(list(od), list('cabde'))
@@ -418,7 +418,7 @@ def test_move_to_end(self):
418418
with self.assertRaises(KeyError):
419419
od.move_to_end('x')
420420
with self.assertRaises(KeyError):
421-
od.move_to_end('x', 0)
421+
od.move_to_end('x', False)
422422

423423
def test_move_to_end_issue25406(self):
424424
OrderedDict = self.OrderedDict

Lib/test/test_unicode.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2820,15 +2820,15 @@ def test_asucs4(self):
28202820
for s in ['abc', '\xa1\xa2', '\u4f60\u597d', 'a\U0001f600',
28212821
'a\ud800b\udfffc', '\ud834\udd1e']:
28222822
l = len(s)
2823-
self.assertEqual(unicode_asucs4(s, l, 1), s+'\0')
2824-
self.assertEqual(unicode_asucs4(s, l, 0), s+'\uffff')
2825-
self.assertEqual(unicode_asucs4(s, l+1, 1), s+'\0\uffff')
2826-
self.assertEqual(unicode_asucs4(s, l+1, 0), s+'\0\uffff')
2827-
self.assertRaises(SystemError, unicode_asucs4, s, l-1, 1)
2828-
self.assertRaises(SystemError, unicode_asucs4, s, l-2, 0)
2823+
self.assertEqual(unicode_asucs4(s, l, True), s+'\0')
2824+
self.assertEqual(unicode_asucs4(s, l, False), s+'\uffff')
2825+
self.assertEqual(unicode_asucs4(s, l+1, True), s+'\0\uffff')
2826+
self.assertEqual(unicode_asucs4(s, l+1, False), s+'\0\uffff')
2827+
self.assertRaises(SystemError, unicode_asucs4, s, l-1, True)
2828+
self.assertRaises(SystemError, unicode_asucs4, s, l-2, False)
28292829
s = '\0'.join([s, s])
2830-
self.assertEqual(unicode_asucs4(s, len(s), 1), s+'\0')
2831-
self.assertEqual(unicode_asucs4(s, len(s), 0), s+'\uffff')
2830+
self.assertEqual(unicode_asucs4(s, len(s), True), s+'\0')
2831+
self.assertEqual(unicode_asucs4(s, len(s), False), s+'\uffff')
28322832

28332833
# Test PyUnicode_AsUTF8()
28342834
@support.cpython_only

Lib/threading.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,7 @@ def _acquire_restore(self, x):
262262
def _is_owned(self):
263263
# Return True if lock is owned by current_thread.
264264
# This method is called only if _lock doesn't have _is_owned().
265-
if self._lock.acquire(0):
265+
if self._lock.acquire(False):
266266
self._lock.release()
267267
return False
268268
else:

Lib/tkinter/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2241,7 +2241,7 @@ class Tk(Misc, Wm):
22412241
_w = '.'
22422242

22432243
def __init__(self, screenName=None, baseName=None, className='Tk',
2244-
useTk=1, sync=0, use=None):
2244+
useTk=True, sync=False, use=None):
22452245
"""Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
22462246
be created. BASENAME will be used for the identification of the profile file (see
22472247
readprofile).
@@ -2259,7 +2259,7 @@ def __init__(self, screenName=None, baseName=None, className='Tk',
22592259
baseName, ext = os.path.splitext(baseName)
22602260
if ext not in ('.py', '.pyc'):
22612261
baseName = baseName + ext
2262-
interactive = 0
2262+
interactive = False
22632263
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
22642264
if useTk:
22652265
self._loadtk()
@@ -2361,7 +2361,7 @@ def __getattr__(self, attr):
23612361
# copied into the Pack, Place or Grid class.
23622362

23632363

2364-
def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
2364+
def Tcl(screenName=None, baseName=None, className='Tk', useTk=False):
23652365
return Tk(screenName, baseName, className, useTk)
23662366

23672367

Modules/_io/_iomodule.c

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -383,8 +383,10 @@ _io_open_impl(PyObject *module, PyObject *file, const char *mode,
383383
encoding = "utf-8";
384384
}
385385
#endif
386-
raw = PyObject_CallFunction(RawIO_class,
387-
"OsiO", path_or_fd, rawmode, closefd, opener);
386+
raw = PyObject_CallFunction(RawIO_class, "OsOO",
387+
path_or_fd, rawmode,
388+
closefd ? Py_True : Py_False,
389+
opener);
388390
}
389391

390392
if (raw == NULL)
@@ -476,10 +478,10 @@ _io_open_impl(PyObject *module, PyObject *file, const char *mode,
476478

477479
/* wraps into a TextIOWrapper */
478480
wrapper = PyObject_CallFunction((PyObject *)&PyTextIOWrapper_Type,
479-
"Osssi",
481+
"OsssO",
480482
buffer,
481483
encoding, errors, newline,
482-
line_buffering);
484+
line_buffering ? Py_True : Py_False);
483485
if (wrapper == NULL)
484486
goto error;
485487
result = wrapper;

Modules/_io/stringio.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -714,9 +714,9 @@ _io_StringIO___init___impl(stringio *self, PyObject *value,
714714
}
715715

716716
if (self->readuniversal) {
717-
self->decoder = PyObject_CallFunction(
717+
self->decoder = PyObject_CallFunctionObjArgs(
718718
(PyObject *)&PyIncrementalNewlineDecoder_Type,
719-
"Oi", Py_None, (int) self->readtranslate);
719+
Py_None, self->readtranslate ? Py_True : Py_False, NULL);
720720
if (self->decoder == NULL)
721721
return -1;
722722
}

Modules/_io/textio.c

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -880,9 +880,9 @@ _textiowrapper_set_decoder(textio *self, PyObject *codec_info,
880880
return -1;
881881

882882
if (self->readuniversal) {
883-
PyObject *incrementalDecoder = PyObject_CallFunction(
883+
PyObject *incrementalDecoder = PyObject_CallFunctionObjArgs(
884884
(PyObject *)&PyIncrementalNewlineDecoder_Type,
885-
"Oi", self->decoder, (int)self->readtranslate);
885+
self->decoder, self->readtranslate ? Py_True : Py_False, NULL);
886886
if (incrementalDecoder == NULL)
887887
return -1;
888888
Py_CLEAR(self->decoder);
@@ -2591,8 +2591,8 @@ _io_TextIOWrapper_seek_impl(textio *self, PyObject *cookieObj, int whence)
25912591
}
25922592
Py_XSETREF(self->snapshot, snapshot);
25932593

2594-
decoded = _PyObject_CallMethodId(self->decoder, &PyId_decode,
2595-
"Oi", input_chunk, (int)cookie.need_eof);
2594+
decoded = _PyObject_CallMethodIdObjArgs(self->decoder, &PyId_decode,
2595+
input_chunk, cookie.need_eof ? Py_True : Py_False, NULL);
25962596

25972597
if (check_decoded(decoded) < 0)
25982598
goto fail;
@@ -2819,7 +2819,7 @@ _io_TextIOWrapper_tell_impl(textio *self)
28192819
if (input == input_end) {
28202820
/* We didn't get enough decoded data; signal EOF to get more. */
28212821
PyObject *decoded = _PyObject_CallMethodId(
2822-
self->decoder, &PyId_decode, "yi", "", /* final = */ 1);
2822+
self->decoder, &PyId_decode, "yO", "", /* final = */ Py_True);
28232823
if (check_decoded(decoded) < 0)
28242824
goto fail;
28252825
chars_decoded += PyUnicode_GET_LENGTH(decoded);

Modules/itertoolsmodule.c

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1059,10 +1059,10 @@ cycle_reduce(cycleobject *lz, PyObject *Py_UNUSED(ignored))
10591059
}
10601060
Py_DECREF(res);
10611061
}
1062-
return Py_BuildValue("O(N)(Oi)", Py_TYPE(lz), it, lz->saved, 1);
1062+
return Py_BuildValue("O(N)(OO)", Py_TYPE(lz), it, lz->saved, Py_True);
10631063
}
1064-
return Py_BuildValue("O(O)(Oi)", Py_TYPE(lz), lz->it, lz->saved,
1065-
lz->firstpass);
1064+
return Py_BuildValue("O(O)(OO)", Py_TYPE(lz), lz->it, lz->saved,
1065+
lz->firstpass ? Py_True : Py_False);
10661066
}
10671067

10681068
static PyObject *

Modules/main.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ pymain_run_module(const wchar_t *modname, int set_argv0)
292292
Py_DECREF(runmodule);
293293
return pymain_exit_err_print();
294294
}
295-
runargs = Py_BuildValue("(Oi)", module, set_argv0);
295+
runargs = PyTuple_Pack(2, module, set_argv0 ? Py_True : Py_False);
296296
if (runargs == NULL) {
297297
fprintf(stderr,
298298
"Could not create arguments for runpy._run_module_as_main\n");

Modules/parsermodule.c

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1080,25 +1080,20 @@ parser__pickler(PyObject *self, PyObject *args)
10801080
NOTE(ARGUNUSED(self))
10811081
PyObject *result = NULL;
10821082
PyObject *st = NULL;
1083-
PyObject *empty_dict = NULL;
10841083

10851084
if (PyArg_ParseTuple(args, "O!:_pickler", &PyST_Type, &st)) {
10861085
PyObject *newargs;
10871086
PyObject *tuple;
10881087

1089-
if ((empty_dict = PyDict_New()) == NULL)
1090-
goto finally;
1091-
if ((newargs = Py_BuildValue("Oi", st, 1)) == NULL)
1092-
goto finally;
1093-
tuple = parser_st2tuple((PyST_Object*)NULL, newargs, empty_dict);
1088+
if ((newargs = PyTuple_Pack(2, st, Py_True)) == NULL)
1089+
return NULL;
1090+
tuple = parser_st2tuple((PyST_Object*)NULL, newargs, NULL);
10941091
if (tuple != NULL) {
10951092
result = Py_BuildValue("O(O)", pickle_constructor, tuple);
10961093
Py_DECREF(tuple);
10971094
}
10981095
Py_DECREF(newargs);
10991096
}
1100-
finally:
1101-
Py_XDECREF(empty_dict);
11021097

11031098
return (result);
11041099
}

Objects/fileobject.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,9 @@ PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const c
3838
io = PyImport_ImportModule("_io");
3939
if (io == NULL)
4040
return NULL;
41-
stream = _PyObject_CallMethodId(io, &PyId_open, "isisssi", fd, mode,
41+
stream = _PyObject_CallMethodId(io, &PyId_open, "isisssO", fd, mode,
4242
buffering, encoding, errors,
43-
newline, closefd);
43+
newline, closefd ? Py_True : Py_False);
4444
Py_DECREF(io);
4545
if (stream == NULL)
4646
return NULL;

0 commit comments

Comments
 (0)