[Python-checkins] gh-105751: Cleanup test_ctypes imports (#105803)

vstinner webhook-mailer at python.org
Wed Jun 14 19:31:49 EDT 2023


https://github.com/python/cpython/commit/698a0da7d440856a90b45964e9082b5a55387b80
commit: 698a0da7d440856a90b45964e9082b5a55387b80
branch: main
author: Victor Stinner <vstinner at python.org>
committer: vstinner <vstinner at python.org>
date: 2023-06-14T23:31:45Z
summary:

gh-105751: Cleanup test_ctypes imports (#105803)

* Move imports at top level and sort imports.
* Replace c_buffer() with create_string_buffer(): c_buffer is a
  deprecated alias.
* PEP 8: Add empty lines for readability between imports and classes.

files:
M Lib/test/test_ctypes/test_anon.py
M Lib/test/test_ctypes/test_array_in_pointer.py
M Lib/test/test_ctypes/test_as_parameter.py
M Lib/test/test_ctypes/test_bitfields.py
M Lib/test/test_ctypes/test_buffers.py
M Lib/test/test_ctypes/test_bytes.py
M Lib/test/test_ctypes/test_byteswap.py
M Lib/test/test_ctypes/test_callbacks.py
M Lib/test/test_ctypes/test_cast.py
M Lib/test/test_ctypes/test_cfuncs.py
M Lib/test/test_ctypes/test_checkretval.py
M Lib/test/test_ctypes/test_errno.py
M Lib/test/test_ctypes/test_frombuffer.py
M Lib/test/test_ctypes/test_funcptr.py
M Lib/test/test_ctypes/test_functions.py
M Lib/test/test_ctypes/test_incomplete.py
M Lib/test/test_ctypes/test_internals.py
M Lib/test/test_ctypes/test_keeprefs.py
M Lib/test/test_ctypes/test_libc.py
M Lib/test/test_ctypes/test_loading.py
M Lib/test/test_ctypes/test_macholib.py
M Lib/test/test_ctypes/test_memfunctions.py
M Lib/test/test_ctypes/test_numbers.py
M Lib/test/test_ctypes/test_objects.py
M Lib/test/test_ctypes/test_parameters.py
M Lib/test/test_ctypes/test_pep3118.py
M Lib/test/test_ctypes/test_pickling.py
M Lib/test/test_ctypes/test_pointers.py
M Lib/test/test_ctypes/test_prototypes.py
M Lib/test/test_ctypes/test_python_api.py
M Lib/test/test_ctypes/test_random_things.py
M Lib/test/test_ctypes/test_refcounts.py
M Lib/test/test_ctypes/test_repr.py
M Lib/test/test_ctypes/test_returnfuncptrs.py
M Lib/test/test_ctypes/test_slicing.py
M Lib/test/test_ctypes/test_stringptr.py
M Lib/test/test_ctypes/test_strings.py
M Lib/test/test_ctypes/test_struct_fields.py
M Lib/test/test_ctypes/test_structures.py
M Lib/test/test_ctypes/test_unaligned_structures.py
M Lib/test/test_ctypes/test_unicode.py
M Lib/test/test_ctypes/test_values.py
M Lib/test/test_ctypes/test_varsize_struct.py
M Lib/test/test_ctypes/test_win32.py
M Lib/test/test_ctypes/test_wintypes.py

diff --git a/Lib/test/test_ctypes/test_anon.py b/Lib/test/test_ctypes/test_anon.py
index 704f7a3d38a5..b36397b510fe 100644
--- a/Lib/test/test_ctypes/test_anon.py
+++ b/Lib/test/test_ctypes/test_anon.py
@@ -2,6 +2,7 @@
 import test.support
 from ctypes import c_int, Union, Structure, sizeof
 
+
 class AnonTest(unittest.TestCase):
 
     def test_anon(self):
@@ -69,5 +70,6 @@ class Y(Structure):
         self.assertEqual(Y._.offset, sizeof(c_int))
         self.assertEqual(Y.y.offset, sizeof(c_int) * 2)
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_array_in_pointer.py b/Lib/test/test_ctypes/test_array_in_pointer.py
index a149aa9463f3..b7c96b2fa499 100644
--- a/Lib/test/test_ctypes/test_array_in_pointer.py
+++ b/Lib/test/test_ctypes/test_array_in_pointer.py
@@ -1,21 +1,24 @@
+import binascii
+import re
 import unittest
 from ctypes import c_byte, Structure, POINTER, cast
-from binascii import hexlify
-import re
+
 
 def dump(obj):
     # helper function to dump memory contents in hex, with a hyphen
     # between the bytes.
-    h = hexlify(memoryview(obj)).decode()
+    h = binascii.hexlify(memoryview(obj)).decode()
     return re.sub(r"(..)", r"\1-", h)[:-1]
 
 
 class Value(Structure):
     _fields_ = [("val", c_byte)]
 
+
 class Container(Structure):
     _fields_ = [("pvalues", POINTER(Value))]
 
+
 class Test(unittest.TestCase):
     def test(self):
         # create an array of 4 values
@@ -60,5 +63,6 @@ def test_2(self):
             ([1, 2, 3, 4], "01-02-03-04")
         )
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_as_parameter.py b/Lib/test/test_ctypes/test_as_parameter.py
index 33b7bd3fadea..e842d526c53a 100644
--- a/Lib/test/test_ctypes/test_as_parameter.py
+++ b/Lib/test/test_ctypes/test_as_parameter.py
@@ -16,9 +16,11 @@
     # fake to enable this test on Linux
     CALLBACK_FUNCTYPE = CFUNCTYPE
 
+
 class POINT(Structure):
     _fields_ = [("x", c_int), ("y", c_int)]
 
+
 class BasicWrapTestCase(unittest.TestCase):
     def wrap(self, param):
         return param
@@ -71,8 +73,6 @@ def callback(v):
         f(self.wrap(2**18), self.wrap(cb))
         self.assertEqual(args, expected)
 
-    ################################################################
-
     def test_callbacks(self):
         f = dll._testfunc_callback_i_if
         f.restype = c_int
@@ -194,8 +194,6 @@ class S8I(Structure):
                              (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9))
 
     def test_recursive_as_param(self):
-        from ctypes import c_int
-
         class A(object):
             pass
 
@@ -205,8 +203,6 @@ class A(object):
             c_int.from_param(a)
 
 
-#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
 class AsParamWrapper(object):
     def __init__(self, param):
         self._as_parameter_ = param
@@ -214,7 +210,6 @@ def __init__(self, param):
 class AsParamWrapperTestCase(BasicWrapTestCase):
     wrap = AsParamWrapper
 
-#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
 class AsParamPropertyWrapper(object):
     def __init__(self, param):
@@ -227,7 +222,6 @@ def getParameter(self):
 class AsParamPropertyWrapperTestCase(BasicWrapTestCase):
     wrap = AsParamPropertyWrapper
 
-#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
 if __name__ == '__main__':
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_bitfields.py b/Lib/test/test_ctypes/test_bitfields.py
index 9ffa634dbf70..d8eb2d668a6a 100644
--- a/Lib/test/test_ctypes/test_bitfields.py
+++ b/Lib/test/test_ctypes/test_bitfields.py
@@ -1,13 +1,13 @@
+import _ctypes_test
+import os
+import unittest
 from ctypes import (CDLL, Structure, sizeof, POINTER, byref, alignment,
                     LittleEndianStructure, BigEndianStructure,
                     c_byte, c_ubyte, c_char, c_char_p, c_void_p, c_wchar,
                     c_uint32, c_uint64,
                     c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong)
 from test import support
-import unittest
-import os
 
-import _ctypes_test
 
 class BITS(Structure):
     _fields_ = [("A", c_int, 1),
@@ -56,6 +56,7 @@ def test_shorts(self):
                 setattr(b, name, i)
                 self.assertEqual(getattr(b, name), func(byref(b), name.encode('ascii')))
 
+
 signed_int_types = (c_byte, c_short, c_int, c_long, c_longlong)
 unsigned_int_types = (c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong)
 int_types = unsigned_int_types + signed_int_types
@@ -117,7 +118,6 @@ class X(Structure):
             x.a, x.b = 0, -1
             self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 7, 0))
 
-
     def fail_fields(self, *fields):
         return self.get_except(type(Structure), "X", (),
                                {"_fields_": fields})
@@ -194,7 +194,6 @@ class X(Structure):
         self.assertEqual(X.b.offset, sizeof(c_short)*1)
         self.assertEqual(X.c.offset, sizeof(c_short)*2)
 
-
     def get_except(self, func, *args, **kw):
         try:
             func(*args, **kw)
@@ -291,5 +290,6 @@ class Big(BigEndianStructure):
         x.c = 2
         self.assertEqual(b, b'\xab\xcd\xef\x12')
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_buffers.py b/Lib/test/test_ctypes/test_buffers.py
index e446f9e85f92..468f41eb7cf4 100644
--- a/Lib/test/test_ctypes/test_buffers.py
+++ b/Lib/test/test_ctypes/test_buffers.py
@@ -1,9 +1,9 @@
+import unittest
 from ctypes import (create_string_buffer, create_unicode_buffer, sizeof,
                     c_char, c_wchar)
-import unittest
 
-class StringBufferTestCase(unittest.TestCase):
 
+class StringBufferTestCase(unittest.TestCase):
     def test_buffer(self):
         b = create_string_buffer(32)
         self.assertEqual(len(b), 32)
diff --git a/Lib/test/test_ctypes/test_bytes.py b/Lib/test/test_ctypes/test_bytes.py
index 3538ed7d7197..fa11e1bbd49f 100644
--- a/Lib/test/test_ctypes/test_bytes.py
+++ b/Lib/test/test_ctypes/test_bytes.py
@@ -1,8 +1,10 @@
 """Test where byte objects are accepted"""
 import sys
 import unittest
+from _ctypes import _SimpleCData
 from ctypes import Structure, c_char, c_char_p, c_wchar, c_wchar_p
 
+
 class BytesTest(unittest.TestCase):
     def test_c_char(self):
         x = c_char(b"x")
@@ -55,7 +57,6 @@ class X(Structure):
 
     @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test')
     def test_BSTR(self):
-        from _ctypes import _SimpleCData
         class BSTR(_SimpleCData):
             _type_ = "X"
 
diff --git a/Lib/test/test_ctypes/test_byteswap.py b/Lib/test/test_ctypes/test_byteswap.py
index 7507c07d8a8a..2986e8a177a4 100644
--- a/Lib/test/test_ctypes/test_byteswap.py
+++ b/Lib/test/test_ctypes/test_byteswap.py
@@ -1,6 +1,9 @@
-import sys, unittest, struct, math, ctypes
-from binascii import hexlify
-
+import binascii
+import ctypes
+import math
+import struct
+import sys
+import unittest
 from ctypes import (Structure, Union, LittleEndianUnion, BigEndianUnion,
                     BigEndianStructure, LittleEndianStructure,
                     POINTER, sizeof, cast,
@@ -9,8 +12,10 @@
                     c_long, c_ulong, c_longlong, c_ulonglong,
                     c_uint32, c_float, c_double)
 
+
 def bin(s):
-    return hexlify(memoryview(s)).decode().upper()
+    return binascii.hexlify(memoryview(s)).decode().upper()
+
 
 # Each *simple* type that supports different byte orders has an
 # __ctype_be__ attribute that specifies the same type in BIG ENDIAN
@@ -366,5 +371,6 @@ class TestUnion(parent):
                 self.assertEqual(s.point.x, 1)
                 self.assertEqual(s.point.y, 2)
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_callbacks.py b/Lib/test/test_ctypes/test_callbacks.py
index 50c2650cb345..582677b832e5 100644
--- a/Lib/test/test_ctypes/test_callbacks.py
+++ b/Lib/test/test_ctypes/test_callbacks.py
@@ -1,24 +1,25 @@
+import _ctypes_test
+import ctypes
 import functools
+import gc
+import math
 import sys
 import unittest
-from test import support
-
-import ctypes
+from _ctypes import CTYPES_MAX_ARGCOUNT
 from ctypes import (CDLL, cdll, Structure, CFUNCTYPE,
                     ArgumentError, POINTER, sizeof,
                     c_byte, c_ubyte, c_char, c_char_p,
                     c_short, c_ushort, c_int, c_uint,
                     c_long, c_longlong, c_ulonglong, c_ulong,
                     c_float, c_double, c_longdouble, py_object)
-from _ctypes import CTYPES_MAX_ARGCOUNT
-import _ctypes_test
+from ctypes.util import find_library
+from test import support
 
 
 class Callbacks(unittest.TestCase):
     functype = CFUNCTYPE
 
 ##    def tearDown(self):
-##        import gc
 ##        gc.collect()
 
     def callback(self, *args):
@@ -81,7 +82,6 @@ def test_ulonglong(self):
 
     def test_float(self):
         # only almost equal: double -> float -> double
-        import math
         self.check_type(c_float, math.e)
         self.check_type(c_float, -math.e)
 
@@ -138,7 +138,6 @@ def func(self): pass
             def __init__(self):
                 self.v = proto(self.func)
 
-        import gc
         for i in range(32):
             X()
         gc.collect()
@@ -147,7 +146,6 @@ def __init__(self):
         self.assertEqual(len(live), 0)
 
     def test_issue12483(self):
-        import gc
         class Nasty:
             def __del__(self):
                 gc.collect()
@@ -172,8 +170,6 @@ class StdcallCallbacks(Callbacks):
         functype = ctypes.WINFUNCTYPE
 
 
-################################################################
-
 class SampleCallbacksTestCase(unittest.TestCase):
 
     def test_integrate(self):
@@ -197,7 +193,6 @@ def func(x):
         self.assertLess(diff, 0.01, "%s not less than 0.01" % diff)
 
     def test_issue_8959_a(self):
-        from ctypes.util import find_library
         libc_path = find_library("c")
         if not libc_path:
             self.skipTest('could not find libc')
diff --git a/Lib/test/test_ctypes/test_cast.py b/Lib/test/test_ctypes/test_cast.py
index abff120d8b0e..604f44f03d61 100644
--- a/Lib/test/test_ctypes/test_cast.py
+++ b/Lib/test/test_ctypes/test_cast.py
@@ -4,8 +4,8 @@
                     c_void_p, c_char_p, c_wchar_p,
                     c_byte, c_short, c_int)
 
-class Test(unittest.TestCase):
 
+class Test(unittest.TestCase):
     def test_array2pointer(self):
         array = (c_int * 3)(42, 17, 2)
 
@@ -80,7 +80,7 @@ def test_char_p(self):
     def test_wchar_p(self):
         s = c_wchar_p("hiho")
         self.assertEqual(cast(cast(s, c_void_p), c_wchar_p).value,
-                             "hiho")
+                         "hiho")
 
     def test_bad_type_arg(self):
         # The type argument must be a ctypes pointer type.
@@ -95,5 +95,6 @@ class MyUnion(Union):
             _fields_ = [("a", c_int)]
         self.assertRaises(TypeError, cast, array, MyUnion)
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_cfuncs.py b/Lib/test/test_ctypes/test_cfuncs.py
index 6969aed81891..6ff0878a35da 100644
--- a/Lib/test/test_ctypes/test_cfuncs.py
+++ b/Lib/test/test_ctypes/test_cfuncs.py
@@ -1,11 +1,11 @@
-import unittest
+import _ctypes_test
 import ctypes
+import unittest
 from ctypes import (CDLL,
                     c_byte, c_ubyte, c_char,
                     c_short, c_ushort, c_int, c_uint,
                     c_long, c_ulong, c_longlong, c_ulonglong,
                     c_float, c_double, c_longdouble)
-import _ctypes_test
 
 
 class CFunctions(unittest.TestCase):
@@ -190,6 +190,7 @@ def test_void(self):
         self.assertEqual(self._dll.tv_i(-42), None)
         self.assertEqual(self.S(), -42)
 
+
 # The following repeats the above tests with stdcall functions (where
 # they are available)
 if hasattr(ctypes, 'WinDLL'):
diff --git a/Lib/test/test_ctypes/test_checkretval.py b/Lib/test/test_ctypes/test_checkretval.py
index 176102d5a89e..5dc9e25aa382 100644
--- a/Lib/test/test_ctypes/test_checkretval.py
+++ b/Lib/test/test_ctypes/test_checkretval.py
@@ -1,3 +1,4 @@
+import _ctypes_test
 import ctypes
 import unittest
 from ctypes import CDLL, c_int
@@ -11,10 +12,7 @@ def _check_retval_(value):
 
 
 class Test(unittest.TestCase):
-
     def test_checkretval(self):
-
-        import _ctypes_test
         dll = CDLL(_ctypes_test.__file__)
         self.assertEqual(42, dll._testfunc_p_p(42))
 
@@ -34,6 +32,5 @@ def test_oledll(self):
         self.assertRaises(OSError, oleaut32.CreateTypeLib2, 0, None, None)
 
 
-
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_errno.py b/Lib/test/test_ctypes/test_errno.py
index 3376322299d2..65d99c1e492a 100644
--- a/Lib/test/test_ctypes/test_errno.py
+++ b/Lib/test/test_ctypes/test_errno.py
@@ -1,10 +1,12 @@
-import unittest, os, errno
-import threading
-
 import ctypes
+import errno
+import os
+import threading
+import unittest
 from ctypes import CDLL, c_int, c_char_p, c_wchar_p, get_errno, set_errno
 from ctypes.util import find_library
 
+
 class Test(unittest.TestCase):
     def test_open(self):
         libc_name = find_library("c")
diff --git a/Lib/test/test_ctypes/test_frombuffer.py b/Lib/test/test_ctypes/test_frombuffer.py
index e3e126738784..d4e161f864d4 100644
--- a/Lib/test/test_ctypes/test_frombuffer.py
+++ b/Lib/test/test_ctypes/test_frombuffer.py
@@ -1,7 +1,10 @@
 import array
 import gc
 import unittest
-from ctypes import Structure, Union, Array, sizeof, c_char, c_int
+from ctypes import (Structure, Union, Array, sizeof,
+                    _Pointer, _SimpleCData, _CFuncPtr,
+                    c_char, c_int)
+
 
 class X(Structure):
     _fields_ = [("c_int", c_int)]
@@ -9,6 +12,7 @@ class X(Structure):
     def __init__(self):
         self._init_called = True
 
+
 class Test(unittest.TestCase):
     def test_from_buffer(self):
         a = array.array("i", range(16))
@@ -121,8 +125,6 @@ def test_from_buffer_copy_with_offset(self):
             (c_int * 1).from_buffer_copy(a, 16 * sizeof(c_int))
 
     def test_abstract(self):
-        from ctypes import _Pointer, _SimpleCData, _CFuncPtr
-
         self.assertRaises(TypeError, Array.from_buffer, bytearray(10))
         self.assertRaises(TypeError, Structure.from_buffer, bytearray(10))
         self.assertRaises(TypeError, Union.from_buffer, bytearray(10))
@@ -137,5 +139,6 @@ def test_abstract(self):
         self.assertRaises(TypeError, _Pointer.from_buffer_copy, b"123")
         self.assertRaises(TypeError, _SimpleCData.from_buffer_copy, b"123")
 
+
 if __name__ == '__main__':
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_funcptr.py b/Lib/test/test_ctypes/test_funcptr.py
index 72684d6d1cd1..0ea3f3581bba 100644
--- a/Lib/test/test_ctypes/test_funcptr.py
+++ b/Lib/test/test_ctypes/test_funcptr.py
@@ -1,9 +1,10 @@
 import _ctypes_test
 import ctypes
 import unittest
-from ctypes import (CDLL, Structure, CFUNCTYPE, sizeof,
+from ctypes import (CDLL, Structure, CFUNCTYPE, sizeof, _CFuncPtr,
                     c_void_p, c_char_p, c_char, c_int, c_uint, c_long)
 
+
 try:
     WINFUNCTYPE = ctypes.WINFUNCTYPE
 except AttributeError:
@@ -127,8 +128,6 @@ def c_string(init):
         self.assertEqual(strtok(None, b"\n"), None)
 
     def test_abstract(self):
-        from ctypes import _CFuncPtr
-
         self.assertRaises(TypeError, _CFuncPtr, 13, "name", 42, "iid")
 
 
diff --git a/Lib/test/test_ctypes/test_functions.py b/Lib/test/test_ctypes/test_functions.py
index 7979f0e36b30..f8591463c18a 100644
--- a/Lib/test/test_ctypes/test_functions.py
+++ b/Lib/test/test_ctypes/test_functions.py
@@ -1,17 +1,14 @@
-"""
-Here is probably the place to write the docs, since the test-cases
-show how the type behave.
-
-Later...
-"""
-
+import _ctypes_test
 import ctypes
+import sys
+import unittest
 from ctypes import (CDLL, Structure, Array, CFUNCTYPE,
                     byref, POINTER, pointer, ArgumentError,
                     c_char, c_wchar, c_byte, c_char_p,
                     c_short, c_int, c_long, c_longlong,
                     c_float, c_double, c_longdouble)
-import sys, unittest
+from _ctypes import _Pointer,  _SimpleCData
+
 
 try:
     WINFUNCTYPE = ctypes.WINFUNCTYPE
@@ -19,16 +16,20 @@
     # fake to enable this test on Linux
     WINFUNCTYPE = CFUNCTYPE
 
-import _ctypes_test
 dll = CDLL(_ctypes_test.__file__)
 if sys.platform == "win32":
     windll = ctypes.WinDLL(_ctypes_test.__file__)
 
+
 class POINT(Structure):
     _fields_ = [("x", c_int), ("y", c_int)]
+
+
 class RECT(Structure):
     _fields_ = [("left", c_int), ("top", c_int),
                 ("right", c_int), ("bottom", c_int)]
+
+
 class FunctionTestCase(unittest.TestCase):
 
     def test_mro(self):
@@ -44,12 +45,10 @@ class X(object, Array):
                 _length_ = 5
                 _type_ = "i"
 
-        from _ctypes import _Pointer
         with self.assertRaises(TypeError):
             class X(object, _Pointer):
                 pass
 
-        from _ctypes import _SimpleCData
         with self.assertRaises(TypeError):
             class X(object, _SimpleCData):
                 _type_ = "i"
@@ -407,5 +406,6 @@ def callback(*args):
         callback = proto(callback)
         self.assertRaises(ArgumentError, lambda: callback((1, 2, 3, 4), POINT()))
 
+
 if __name__ == '__main__':
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_incomplete.py b/Lib/test/test_ctypes/test_incomplete.py
index 552effaa3db9..9f859793d88a 100644
--- a/Lib/test/test_ctypes/test_incomplete.py
+++ b/Lib/test/test_ctypes/test_incomplete.py
@@ -3,13 +3,9 @@
 import warnings
 from ctypes import Structure, POINTER, pointer, c_char_p
 
-################################################################
-#
-# The incomplete pointer example from the tutorial
-#
 
+# The incomplete pointer example from the tutorial
 class TestSetPointerType(unittest.TestCase):
-
     def tearDown(self):
         # to not leak references, we must clean _pointer_type_cache
         ctypes._reset_cache()
@@ -49,7 +45,6 @@ class cell(Structure):
         with self.assertWarns(DeprecationWarning):
             ctypes.SetPointerType(lpcell, cell)
 
-################################################################
 
 if __name__ == '__main__':
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_internals.py b/Lib/test/test_ctypes/test_internals.py
index 06826eb9ebd7..763a5e8b0f08 100644
--- a/Lib/test/test_ctypes/test_internals.py
+++ b/Lib/test/test_ctypes/test_internals.py
@@ -1,7 +1,4 @@
 # This tests the internal _objects attribute
-import sys
-import unittest
-from ctypes import Structure, POINTER, c_char_p, c_int
 
 # XXX This test must be reviewed for correctness!!!
 
@@ -14,6 +11,11 @@
 #
 # What about pointers?
 
+import sys
+import unittest
+from ctypes import Structure, POINTER, c_char_p, c_int
+
+
 class ObjectsTestCase(unittest.TestCase):
     def assertSame(self, a, b):
         self.assertEqual(id(a), id(b))
@@ -96,5 +98,6 @@ class X(Structure):
 ##XXX        print x.data[0]
 ##XXX        print x.data._objects
 
+
 if __name__ == '__main__':
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_keeprefs.py b/Lib/test/test_ctypes/test_keeprefs.py
index 6fb0628ad3b6..f93e3f267694 100644
--- a/Lib/test/test_ctypes/test_keeprefs.py
+++ b/Lib/test/test_ctypes/test_keeprefs.py
@@ -1,6 +1,8 @@
+import gc
 import sys
 import unittest
-from ctypes import Structure, POINTER, pointer, c_char_p, c_int
+from ctypes import (Structure, POINTER, pointer,  _pointer_type_cache,
+                    c_char_p, c_int)
 
 
 class SimpleTestCase(unittest.TestCase):
@@ -20,6 +22,7 @@ def test_ccharp(self):
         x = c_char_p(b"spam")
         self.assertEqual(x._objects, b"spam")
 
+
 class StructureTestCase(unittest.TestCase):
     def test_cint_struct(self):
         class X(Structure):
@@ -66,6 +69,7 @@ class RECT(Structure):
         r.lr = POINT()
         self.assertEqual(r._objects, {'0': {}, '1': {}})
 
+
 class ArrayTestCase(unittest.TestCase):
     def test_cint_array(self):
         INTARR = c_int * 3
@@ -89,12 +93,14 @@ class X(Structure):
         x.a = ia
         self.assertEqual(x._objects, {'1': {}})
 
+
 class PointerTestCase(unittest.TestCase):
     def test_p_cint(self):
         i = c_int(42)
         x = pointer(i)
         self.assertEqual(x._objects, {'1': i})
 
+
 class DeletePointerTestCase(unittest.TestCase):
     @unittest.skip('test disabled')
     def test_X(self):
@@ -112,7 +118,6 @@ class X(Structure):
 ##        del x
 ##        print "2?", sys.getrefcount(i)
 ##        del i
-        import gc
         gc.collect()
         for i in range(320):
             c_int(99)
@@ -126,6 +131,7 @@ class X(Structure):
         print("+" * 42)
         print(x._objects)
 
+
 class PointerToStructure(unittest.TestCase):
     def test(self):
         class POINT(Structure):
@@ -147,8 +153,8 @@ class RECT(Structure):
 
         # to avoid leaking when tests are run several times
         # clean up the types left in the cache.
-        from ctypes import _pointer_type_cache
         del _pointer_type_cache[POINT]
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_libc.py b/Lib/test/test_ctypes/test_libc.py
index 8664529f0944..09c76db0bd0b 100644
--- a/Lib/test/test_ctypes/test_libc.py
+++ b/Lib/test/test_ctypes/test_libc.py
@@ -1,10 +1,10 @@
+import _ctypes_test
+import math
 import unittest
-
 from ctypes import (CDLL, CFUNCTYPE, POINTER, create_string_buffer, sizeof,
                     c_void_p, c_char, c_int, c_double, c_size_t)
 
 
-import _ctypes_test
 lib = CDLL(_ctypes_test.__file__)
 
 
@@ -12,12 +12,12 @@ def three_way_cmp(x, y):
     """Return -1 if x < y, 0 if x == y and 1 if x > y"""
     return (x > y) - (x < y)
 
+
 class LibTest(unittest.TestCase):
     def test_sqrt(self):
         lib.my_sqrt.argtypes = c_double,
         lib.my_sqrt.restype = c_double
         self.assertEqual(lib.my_sqrt(4.0), 2.0)
-        import math
         self.assertEqual(lib.my_sqrt(2.0), math.sqrt(2.0))
 
     def test_qsort(self):
@@ -32,5 +32,6 @@ def sort(a, b):
         lib.my_qsort(chars, len(chars)-1, sizeof(c_char), comparefunc(sort))
         self.assertEqual(chars.raw, b"   ,,aaaadmmmnpppsss\x00")
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_loading.py b/Lib/test/test_ctypes/test_loading.py
index 0cbfcf01c0cf..22db97b818c1 100644
--- a/Lib/test/test_ctypes/test_loading.py
+++ b/Lib/test/test_ctypes/test_loading.py
@@ -1,3 +1,5 @@
+import _ctypes
+import _ctypes_test
 import ctypes
 import os
 import shutil
@@ -5,13 +7,14 @@
 import sys
 import test.support
 import unittest
-from test.support import import_helper, os_helper
 from ctypes import CDLL, cdll, addressof, c_void_p, c_char_p
 from ctypes.util import find_library
+from test.support import import_helper, os_helper
 
 
 libc_name = None
 
+
 def setUpModule():
     global libc_name
     if os.name == "nt":
@@ -24,6 +27,7 @@ def setUpModule():
     if test.support.verbose:
         print("libc_name is", libc_name)
 
+
 class LoaderTest(unittest.TestCase):
 
     unknowndll = "xxrandomnamexx"
@@ -33,7 +37,6 @@ def test_load(self):
             test_lib = libc_name
         else:
             if os.name == "nt":
-                import _ctypes_test
                 test_lib = _ctypes_test.__file__
             else:
                 self.skipTest('could not find library to load')
@@ -83,7 +86,6 @@ def test_load_library(self):
     @unittest.skipUnless(os.name == "nt",
                          'test specific to Windows')
     def test_load_ordinal_functions(self):
-        import _ctypes_test
         dll = ctypes.WinDLL(_ctypes_test.__file__)
         # We load the same function both via ordinal and name
         func_ord = dll[2]
@@ -99,14 +101,13 @@ def test_load_ordinal_functions(self):
 
     @unittest.skipUnless(os.name == "nt", 'Windows-specific test')
     def test_1703286_A(self):
-        from _ctypes import LoadLibrary, FreeLibrary
         # On winXP 64-bit, advapi32 loads at an address that does
         # NOT fit into a 32-bit integer.  FreeLibrary must be able
         # to accept this address.
 
         # These are tests for https://bugs.python.org/issue1703286
-        handle = LoadLibrary("advapi32")
-        FreeLibrary(handle)
+        handle = _ctypes.LoadLibrary("advapi32")
+        _ctypes.FreeLibrary(handle)
 
     @unittest.skipUnless(os.name == "nt", 'Windows-specific test')
     def test_1703286_B(self):
@@ -114,7 +115,6 @@ def test_1703286_B(self):
         # above, the (arbitrarily selected) CloseEventLog function
         # also has a high address.  'call_function' should accept
         # addresses so large.
-        from _ctypes import call_function
 
         advapi32 = ctypes.windll.advapi32
         # Calling CloseEventLog with a NULL argument should fail,
@@ -128,7 +128,7 @@ def test_1703286_B(self):
         self.assertTrue(proc)
 
         # This is the real test: call the function via 'call_function'
-        self.assertEqual(0, call_function(proc, (None,)))
+        self.assertEqual(0, _ctypes.call_function(proc, (None,)))
 
     @unittest.skipUnless(os.name == "nt",
                          'test specific to Windows')
diff --git a/Lib/test/test_ctypes/test_macholib.py b/Lib/test/test_ctypes/test_macholib.py
index bc75f1a05a8c..9d9061799562 100644
--- a/Lib/test/test_ctypes/test_macholib.py
+++ b/Lib/test/test_ctypes/test_macholib.py
@@ -1,7 +1,3 @@
-import os
-import sys
-import unittest
-
 # Bob Ippolito:
 #
 # Ok.. the code to find the filename for __getattr__ should look
@@ -31,10 +27,15 @@
 #
 # -bob
 
+import os
+import sys
+import unittest
+
 from ctypes.macholib.dyld import dyld_find
 from ctypes.macholib.dylib import dylib_info
 from ctypes.macholib.framework import framework_info
 
+
 def find_lib(name):
     possible = ['lib'+name+'.dylib', name+'.dylib', name+'.framework/'+name]
     for dylib in possible:
@@ -106,5 +107,6 @@ def test_framework_info(self):
         self.assertEqual(framework_info('P/F.framework/Versions/A/F_debug'),
                          d('P', 'F.framework/Versions/A/F_debug', 'F', 'A', 'debug'))
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_memfunctions.py b/Lib/test/test_ctypes/test_memfunctions.py
index 9d8e156ad5e0..2ff95f619e08 100644
--- a/Lib/test/test_ctypes/test_memfunctions.py
+++ b/Lib/test/test_ctypes/test_memfunctions.py
@@ -1,12 +1,13 @@
 import sys
-from test import support
 import unittest
+from test import support
 from ctypes import (POINTER, sizeof, cast,
                     create_string_buffer, string_at,
                     create_unicode_buffer, wstring_at,
                     memmove, memset,
                     c_char_p, c_byte, c_ubyte, c_wchar)
 
+
 class MemFunctionsTest(unittest.TestCase):
     @unittest.skip('test disabled')
     def test_overflow(self):
@@ -77,5 +78,6 @@ def test_wstring_at(self):
         self.assertEqual(wstring_at(a, 16), "Hello, World\0\0\0\0")
         self.assertEqual(wstring_at(a, 0), "")
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_numbers.py b/Lib/test/test_ctypes/test_numbers.py
index 061876f9f776..052900f519c0 100644
--- a/Lib/test/test_ctypes/test_numbers.py
+++ b/Lib/test/test_ctypes/test_numbers.py
@@ -1,13 +1,14 @@
+import array
 import struct
 import sys
 import unittest
-from array import array
 from operator import truth
 from ctypes import (byref, sizeof, alignment, _SimpleCData,
                     c_char, c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint,
                     c_long, c_ulong, c_longlong, c_ulonglong,
                     c_float, c_double, c_longdouble, c_bool)
 
+
 def valid_ranges(*types):
     # given a sequence of numeric types, collect their _type_
     # attribute, which is a single format character compatible with
@@ -25,6 +26,7 @@ def valid_ranges(*types):
         result.append((min(a, b, c, d), max(a, b, c, d)))
     return result
 
+
 ArgType = type(byref(c_int(0)))
 
 unsigned_types = [c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong]
@@ -36,7 +38,6 @@ def valid_ranges(*types):
 signed_ranges = valid_ranges(*signed_types)
 bool_values = [True, False, 0, 1, -1, 5000, 'test', [], [1]]
 
-################################################################
 
 class NumberTestCase(unittest.TestCase):
 
@@ -152,10 +153,10 @@ def test_int_from_address(self):
             # the array module doesn't support all format codes
             # (no 'q' or 'Q')
             try:
-                array(t._type_)
+                array.array(t._type_)
             except ValueError:
                 continue
-            a = array(t._type_, [100])
+            a = array.array(t._type_, [100])
 
             # v now is an integer at an 'external' memory location
             v = t.from_address(a.buffer_info()[0])
@@ -169,7 +170,7 @@ def test_int_from_address(self):
 
     def test_float_from_address(self):
         for t in float_types:
-            a = array(t._type_, [3.14])
+            a = array.array(t._type_, [3.14])
             v = t.from_address(a.buffer_info()[0])
             self.assertEqual(v.value, a[0])
             self.assertIs(type(v), t)
@@ -178,7 +179,7 @@ def test_float_from_address(self):
             self.assertIs(type(v), t)
 
     def test_char_from_address(self):
-        a = array('b', [0])
+        a = array.array('b', [0])
         a[0] = ord('x')
         v = c_char.from_address(a.buffer_info()[0])
         self.assertEqual(v.value, b'x')
@@ -190,7 +191,7 @@ def test_char_from_address(self):
     # array does not support c_bool / 't'
     @unittest.skip('test disabled')
     def test_bool_from_address(self):
-        a = array(c_bool._type_, [True])
+        a = array.array(c_bool._type_, [True])
         v = t.from_address(a.buffer_info()[0])
         self.assertEqual(v.value, a[0])
         self.assertEqual(type(v) is t)
@@ -217,10 +218,12 @@ def test_float_overflow(self):
     def test_perf(self):
         check_perf()
 
+
 class c_int_S(_SimpleCData):
     _type_ = "i"
     __slots__ = []
 
+
 def run_test(rep, msg, func, arg=None):
 ##    items = [None] * rep
     items = range(rep)
@@ -237,6 +240,7 @@ def run_test(rep, msg, func, arg=None):
         stop = clock()
     print("%15s: %.2f us" % (msg, ((stop-start)*1e6/5/rep)))
 
+
 def check_perf():
     # Construct 5 objects
     from ctypes import c_int
@@ -268,6 +272,7 @@ def check_perf():
 #      c_int_S(): 9.87 us
 #   c_int_S(999): 9.85 us
 
+
 if __name__ == '__main__':
 ##    check_perf()
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_objects.py b/Lib/test/test_ctypes/test_objects.py
index 78b1634115bd..23c92b01a111 100644
--- a/Lib/test/test_ctypes/test_objects.py
+++ b/Lib/test/test_ctypes/test_objects.py
@@ -51,17 +51,18 @@
 >>> x.array._b_base_._objects
 {'0:2': b'spam spam spam'}
 >>>
-
 '''
 
-import unittest, doctest
-
+import doctest
+import unittest
 import test.test_ctypes.test_objects
 
+
 class TestCase(unittest.TestCase):
     def test(self):
         failures, tests = doctest.testmod(test.test_ctypes.test_objects)
         self.assertFalse(failures, 'doctests failed, see output above')
 
+
 if __name__ == '__main__':
     doctest.testmod(test.test_ctypes.test_objects)
diff --git a/Lib/test/test_ctypes/test_parameters.py b/Lib/test/test_ctypes/test_parameters.py
index 02a2bc3839a6..f43819f00499 100644
--- a/Lib/test/test_ctypes/test_parameters.py
+++ b/Lib/test/test_ctypes/test_parameters.py
@@ -1,8 +1,22 @@
+import _ctypes_test
 import unittest
 import test.support
+from ctypes import (CDLL, PyDLL, ArgumentError,
+                    Structure, Array, Union,
+                    _Pointer, _SimpleCData, _CFuncPtr,
+                    POINTER, pointer, byref,
+                    c_void_p, c_char_p, c_wchar_p, py_object,
+                    c_bool,
+                    c_char, c_wchar,
+                    c_byte, c_ubyte,
+                    c_short, c_ushort,
+                    c_int, c_uint,
+                    c_long, c_ulong,
+                    c_longlong, c_ulonglong,
+                    c_float, c_double, c_longdouble)
 
-class SimpleTypesTestCase(unittest.TestCase):
 
+class SimpleTypesTestCase(unittest.TestCase):
     def setUp(self):
         try:
             from _ctypes import set_conversion_mode
@@ -20,7 +34,6 @@ def tearDown(self):
             set_conversion_mode(*self.prev_conv_mode)
 
     def test_subclasses(self):
-        from ctypes import c_void_p, c_char_p
         # ctypes 0.9.5 and before did overwrite from_param in SimpleType_new
         class CVOIDP(c_void_p):
             def from_param(cls, value):
@@ -36,8 +49,6 @@ def from_param(cls, value):
         self.assertEqual(CCHARP.from_param("abc"), "abcabcabcabc")
 
     def test_subclasses_c_wchar_p(self):
-        from ctypes import c_wchar_p
-
         class CWCHARP(c_wchar_p):
             def from_param(cls, value):
                 return value * 3
@@ -47,8 +58,6 @@ def from_param(cls, value):
 
     # XXX Replace by c_char_p tests
     def test_cstrings(self):
-        from ctypes import c_char_p
-
         # c_char_p.from_param on a Python String packs the string
         # into a cparam object
         s = b"123"
@@ -65,8 +74,6 @@ def test_cstrings(self):
         self.assertIs(c_char_p.from_param(a), a)
 
     def test_cw_strings(self):
-        from ctypes import c_wchar_p
-
         c_wchar_p.from_param("123")
 
         self.assertRaises(TypeError, c_wchar_p.from_param, 42)
@@ -76,16 +83,12 @@ def test_cw_strings(self):
         self.assertEqual(type(pa), c_wchar_p)
 
     def test_c_char(self):
-        from ctypes import c_char
-
         with self.assertRaises(TypeError) as cm:
             c_char.from_param(b"abc")
         self.assertEqual(str(cm.exception),
                          "one character bytes, bytearray or integer expected")
 
     def test_c_wchar(self):
-        from ctypes import c_wchar
-
         with self.assertRaises(TypeError) as cm:
             c_wchar.from_param("abc")
         self.assertEqual(str(cm.exception),
@@ -98,7 +101,6 @@ def test_c_wchar(self):
                          "unicode string expected instead of int instance")
 
     def test_int_pointers(self):
-        from ctypes import c_short, c_uint, c_int, c_long, POINTER, pointer
         LPINT = POINTER(c_int)
 
 ##        p = pointer(c_int(42))
@@ -117,7 +119,6 @@ def test_int_pointers(self):
     def test_byref_pointer(self):
         # The from_param class method of POINTER(typ) classes accepts what is
         # returned by byref(obj), it type(obj) == typ
-        from ctypes import c_short, c_uint, c_int, c_long, POINTER, byref
         LPINT = POINTER(c_int)
 
         LPINT.from_param(byref(c_int(42)))
@@ -129,7 +130,6 @@ def test_byref_pointer(self):
 
     def test_byref_pointerpointer(self):
         # See above
-        from ctypes import c_short, c_uint, c_int, c_long, pointer, POINTER, byref
 
         LPLPINT = POINTER(POINTER(c_int))
         LPLPINT.from_param(byref(pointer(c_int(42))))
@@ -140,7 +140,6 @@ def test_byref_pointerpointer(self):
         self.assertRaises(TypeError, LPLPINT.from_param, byref(pointer(c_uint(22))))
 
     def test_array_pointers(self):
-        from ctypes import c_short, c_uint, c_int, c_long, POINTER
         INTARRAY = c_int * 3
         ia = INTARRAY()
         self.assertEqual(len(ia), 3)
@@ -155,9 +154,6 @@ def test_array_pointers(self):
         self.assertRaises(TypeError, LPINT.from_param, c_uint*3)
 
     def test_noctypes_argtype(self):
-        import _ctypes_test
-        from ctypes import CDLL, c_void_p, ArgumentError
-
         func = CDLL(_ctypes_test.__file__)._testfunc_p_p
         func.restype = c_void_p
         # TypeError: has no from_param method
@@ -189,9 +185,6 @@ def from_param(cls, obj):
         self.assertRaises(ArgumentError, func, 99)
 
     def test_abstract(self):
-        from ctypes import (Array, Structure, Union, _Pointer,
-                            _SimpleCData, _CFuncPtr)
-
         self.assertRaises(TypeError, Array.from_param, 42)
         self.assertRaises(TypeError, Structure.from_param, 42)
         self.assertRaises(TypeError, Union.from_param, 42)
@@ -203,7 +196,6 @@ def test_abstract(self):
     def test_issue31311(self):
         # __setstate__ should neither raise a SystemError nor crash in case
         # of a bad __dict__.
-        from ctypes import Structure
 
         class BadStruct(Structure):
             @property
@@ -220,27 +212,6 @@ def __dict__(self):
             WorseStruct().__setstate__({}, b'foo')
 
     def test_parameter_repr(self):
-        from ctypes import (
-            c_bool,
-            c_char,
-            c_wchar,
-            c_byte,
-            c_ubyte,
-            c_short,
-            c_ushort,
-            c_int,
-            c_uint,
-            c_long,
-            c_ulong,
-            c_longlong,
-            c_ulonglong,
-            c_float,
-            c_double,
-            c_longdouble,
-            c_char_p,
-            c_wchar_p,
-            c_void_p,
-        )
         self.assertRegex(repr(c_bool.from_param(True)), r"^<cparam '\?' at 0x[A-Fa-f0-9]+>$")
         self.assertEqual(repr(c_char.from_param(97)), "<cparam 'c' ('a')>")
         self.assertRegex(repr(c_wchar.from_param('a')), r"^<cparam 'u' at 0x[A-Fa-f0-9]+>$")
@@ -265,9 +236,6 @@ def test_parameter_repr(self):
     @test.support.cpython_only
     def test_from_param_result_refcount(self):
         # Issue #99952
-        import _ctypes_test
-        from ctypes import PyDLL, c_int, c_void_p, py_object, Structure
-
         class X(Structure):
             """This struct size is <= sizeof(void*)."""
             _fields_ = [("a", c_void_p)]
@@ -314,7 +282,6 @@ def from_param(cls, value):
 
         self.assertEqual(trace, [1, 2, 3, 4, 5])
 
-################################################################
 
 if __name__ == '__main__':
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_pep3118.py b/Lib/test/test_ctypes/test_pep3118.py
index c8eb584858ca..caecbc8def88 100644
--- a/Lib/test/test_ctypes/test_pep3118.py
+++ b/Lib/test/test_ctypes/test_pep3118.py
@@ -1,3 +1,5 @@
+import re
+import sys
 import unittest
 from ctypes import (CFUNCTYPE, POINTER, sizeof, Union,
                     Structure, LittleEndianStructure, BigEndianStructure,
@@ -5,7 +7,7 @@
                     c_short, c_ushort, c_int, c_uint,
                     c_long, c_ulong, c_longlong, c_ulonglong, c_uint64,
                     c_bool, c_float, c_double, c_longdouble, py_object)
-import re, sys
+
 
 if sys.byteorder == "little":
     THIS_ENDIAN = "<"
@@ -14,6 +16,7 @@
     THIS_ENDIAN = ">"
     OTHER_ENDIAN = "<"
 
+
 def normalize(format):
     # Remove current endian specifier and white space from a format
     # string
@@ -22,8 +25,8 @@ def normalize(format):
     format = format.replace(OTHER_ENDIAN, THIS_ENDIAN)
     return re.sub(r"\s", "", format)
 
-class Test(unittest.TestCase):
 
+class Test(unittest.TestCase):
     def test_native_types(self):
         for tp, fmt, shape, itemtp in native_types:
             ob = tp()
@@ -80,6 +83,7 @@ def test_endian_types(self):
                 print(tp)
                 raise
 
+
 # define some structure classes
 
 class Point(Structure):
@@ -124,6 +128,7 @@ class Complete(Structure):
 PComplete = POINTER(Complete)
 Complete._fields_ = [("a", c_long)]
 
+
 ################################################################
 #
 # This table contains format strings as they look on little endian
@@ -233,17 +238,16 @@ class Complete(Structure):
 
     ]
 
+
 class BEPoint(BigEndianStructure):
     _fields_ = [("x", c_long), ("y", c_long)]
 
 class LEPoint(LittleEndianStructure):
     _fields_ = [("x", c_long), ("y", c_long)]
 
-################################################################
-#
+
 # This table contains format strings as they really look, on both big
 # and little endian machines.
-#
 endian_types = [
     (BEPoint, "T{>l:x:>l:y:}".replace('l', s_long), (), BEPoint),
     (LEPoint * 1, "T{<l:x:<l:y:}".replace('l', s_long), (1,), LEPoint),
@@ -251,5 +255,6 @@ class LEPoint(LittleEndianStructure):
     (POINTER(LEPoint), "&T{<l:x:<l:y:}".replace('l', s_long), (), POINTER(LEPoint)),
     ]
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_pickling.py b/Lib/test/test_ctypes/test_pickling.py
index 1df79be9fbac..0ca42a68f067 100644
--- a/Lib/test/test_ctypes/test_pickling.py
+++ b/Lib/test/test_ctypes/test_pickling.py
@@ -1,10 +1,11 @@
-import unittest
+import _ctypes_test
 import pickle
+import unittest
 from ctypes import (CDLL, Structure, CFUNCTYPE, pointer,
-                    c_void_p, c_char_p, c_wchar_p, c_char, c_wchar, c_int, c_double)
+                    c_void_p, c_char_p, c_wchar_p,
+                    c_char, c_wchar, c_int, c_double)
 
 
-import _ctypes_test
 dll = CDLL(_ctypes_test.__file__)
 
 
@@ -15,9 +16,11 @@ def __init__(self, *args, **kw):
         X.init_called += 1
         self.x = 42
 
+
 class Y(X):
     _fields_ = [("str", c_char_p)]
 
+
 class PickleTest:
     def dumps(self, item):
         return pickle.dumps(item, self.proto)
@@ -75,11 +78,13 @@ def test_wchar(self):
         # Issue 5049
         self.dumps(c_wchar("x"))
 
+
 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
     name = 'PickleTest_%s' % proto
     globals()[name] = type(name,
                            (PickleTest, unittest.TestCase),
                            {'proto': proto})
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_pointers.py b/Lib/test/test_ctypes/test_pointers.py
index 7e25d8276bbb..fd30109aa521 100644
--- a/Lib/test/test_ctypes/test_pointers.py
+++ b/Lib/test/test_ctypes/test_pointers.py
@@ -1,19 +1,24 @@
 import _ctypes_test
+import array
 import ctypes
 import sys
 import unittest
-from ctypes import (CDLL, CFUNCTYPE, Structure, POINTER, pointer, byref, sizeof,
+from ctypes import (CDLL, CFUNCTYPE, Structure,
+                    POINTER, pointer, _Pointer, _pointer_type_cache,
+                    byref, sizeof,
                     c_void_p, c_char_p,
                     c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint,
-                    c_long, c_ulong, c_longlong, c_ulonglong, c_float, c_double)
+                    c_long, c_ulong, c_longlong, c_ulonglong,
+                    c_float, c_double)
+
 
 ctype_types = [c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint,
                  c_long, c_ulong, c_longlong, c_ulonglong, c_double, c_float]
 python_types = [int, int, int, int, int, int,
                 int, int, int, int, float, float]
 
-class PointersTestCase(unittest.TestCase):
 
+class PointersTestCase(unittest.TestCase):
     def test_pointer_crash(self):
 
         class A(POINTER(c_ulong)):
@@ -111,8 +116,7 @@ def test_basics(self):
                 del p[0]
 
     def test_from_address(self):
-        from array import array
-        a = array('i', [100, 200, 300, 400, 500])
+        a = array.array('i', [100, 200, 300, 400, 500])
         addr = a.buffer_info()[0]
 
         p = POINTER(POINTER(c_int))
@@ -134,7 +138,6 @@ class Table(Structure):
 
         pt.contents.c = 33
 
-        from ctypes import _pointer_type_cache
         del _pointer_type_cache[Table]
 
     def test_basic(self):
@@ -205,7 +208,6 @@ def test_pointer_type_name(self):
         self.assertTrue(POINTER(LargeNamedType))
 
         # to not leak references, we must clean _pointer_type_cache
-        from ctypes import _pointer_type_cache
         del _pointer_type_cache[LargeNamedType]
 
     def test_pointer_type_str_name(self):
@@ -214,12 +216,9 @@ def test_pointer_type_str_name(self):
         self.assertTrue(P)
 
         # to not leak references, we must clean _pointer_type_cache
-        from ctypes import _pointer_type_cache
         del _pointer_type_cache[id(P)]
 
     def test_abstract(self):
-        from ctypes import _Pointer
-
         self.assertRaises(TypeError, _Pointer.set_type, 42)
 
 
diff --git a/Lib/test/test_ctypes/test_prototypes.py b/Lib/test/test_ctypes/test_prototypes.py
index 8dff6d669e93..81eb4562c740 100644
--- a/Lib/test/test_ctypes/test_prototypes.py
+++ b/Lib/test/test_ctypes/test_prototypes.py
@@ -1,9 +1,3 @@
-from ctypes import (CDLL, CFUNCTYPE, POINTER, ArgumentError,
-                    pointer, byref, sizeof, addressof,
-                    c_void_p, c_char_p, c_wchar_p, c_char, c_wchar, c_buffer,
-                    c_short, c_int, c_long, c_longlong, c_double)
-import unittest
-
 # IMPORTANT INFO:
 #
 # Consider this call:
@@ -25,8 +19,16 @@
 # In this case, there would have to be an additional reference to the argument...
 
 import _ctypes_test
+import unittest
+from ctypes import (CDLL, CFUNCTYPE, POINTER, ArgumentError,
+                    pointer, byref, sizeof, addressof, create_string_buffer,
+                    c_void_p, c_char_p, c_wchar_p, c_char, c_wchar,
+                    c_short, c_int, c_long, c_longlong, c_double)
+
+
 testdll = CDLL(_ctypes_test.__file__)
 
+
 # Return machine address `a` as a (possibly long) non-negative integer.
 # Starting with Python 2.5, id(anything) is always non-negative, and
 # the ctypes addressof() inherits that via PyLong_FromVoidPtr().
@@ -40,12 +42,13 @@ def positive_address(a):
     assert a >= 0
     return a
 
+
 def c_wbuffer(init):
     n = len(init) + 1
     return (c_wchar * n)(*init)
 
-class CharPointersTestCase(unittest.TestCase):
 
+class CharPointersTestCase(unittest.TestCase):
     def setUp(self):
         func = testdll._testfunc_p_p
         func.restype = c_long
@@ -102,7 +105,7 @@ def test_POINTER_c_char_arg(self):
         self.assertEqual(None, func(c_char_p(None)))
         self.assertEqual(b"123", func(c_char_p(b"123")))
 
-        self.assertEqual(b"123", func(c_buffer(b"123")))
+        self.assertEqual(b"123", func(create_string_buffer(b"123")))
         ca = c_char(b"a")
         self.assertEqual(ord(b"a"), func(pointer(ca))[0])
         self.assertEqual(ord(b"a"), func(byref(ca))[0])
@@ -117,7 +120,7 @@ def test_c_char_p_arg(self):
         self.assertEqual(None, func(c_char_p(None)))
         self.assertEqual(b"123", func(c_char_p(b"123")))
 
-        self.assertEqual(b"123", func(c_buffer(b"123")))
+        self.assertEqual(b"123", func(create_string_buffer(b"123")))
         ca = c_char(b"a")
         self.assertEqual(ord(b"a"), func(pointer(ca))[0])
         self.assertEqual(ord(b"a"), func(byref(ca))[0])
@@ -132,7 +135,7 @@ def test_c_void_p_arg(self):
         self.assertEqual(b"123", func(c_char_p(b"123")))
         self.assertEqual(None, func(c_char_p(None)))
 
-        self.assertEqual(b"123", func(c_buffer(b"123")))
+        self.assertEqual(b"123", func(create_string_buffer(b"123")))
         ca = c_char(b"a")
         self.assertEqual(ord(b"a"), func(pointer(ca))[0])
         self.assertEqual(ord(b"a"), func(byref(ca))[0])
@@ -162,8 +165,8 @@ class X:
         func.argtypes = None
         self.assertEqual(None, func(X()))
 
-class WCharPointersTestCase(unittest.TestCase):
 
+class WCharPointersTestCase(unittest.TestCase):
     def setUp(self):
         func = testdll._testfunc_p_p
         func.restype = c_int
@@ -203,6 +206,7 @@ def test_c_wchar_p_arg(self):
         self.assertEqual("a", func(pointer(ca))[0])
         self.assertEqual("a", func(byref(ca))[0])
 
+
 class ArrayTest(unittest.TestCase):
     def test(self):
         func = testdll._testfunc_ai8
@@ -216,7 +220,6 @@ def test(self):
         def func(): pass
         CFUNCTYPE(None, c_int * 3)(func)
 
-################################################################
 
 if __name__ == '__main__':
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_python_api.py b/Lib/test/test_ctypes/test_python_api.py
index c8b81196609f..77da35855928 100644
--- a/Lib/test/test_ctypes/test_python_api.py
+++ b/Lib/test/test_ctypes/test_python_api.py
@@ -1,20 +1,12 @@
-import unittest
+import _ctypes
 import sys
+import unittest
 from test import support
-from ctypes import (pythonapi, POINTER, c_buffer, sizeof,
+from ctypes import (pythonapi, POINTER, create_string_buffer, sizeof,
                     py_object, c_char_p, c_char, c_long, c_size_t)
 
 
-################################################################
-# This section should be moved into ctypes\__init__.py, when it's ready.
-
-from _ctypes import PyObj_FromPtr
-
-################################################################
-
-
 class PythonAPITestCase(unittest.TestCase):
-
     def test_PyBytes_FromStringAndSize(self):
         PyBytes_FromStringAndSize = pythonapi.PyBytes_FromStringAndSize
 
@@ -58,7 +50,7 @@ def test_PyObj_FromPtr(self):
         s = "abc def ghi jkl"
         ref = sys.getrefcount(s)
         # id(python-object) is the address
-        pyobj = PyObj_FromPtr(id(s))
+        pyobj = _ctypes.PyObj_FromPtr(id(s))
         self.assertIs(s, pyobj)
 
         self.assertEqual(sys.getrefcount(s), ref + 1)
@@ -69,7 +61,7 @@ def test_PyOS_snprintf(self):
         PyOS_snprintf = pythonapi.PyOS_snprintf
         PyOS_snprintf.argtypes = POINTER(c_char), c_size_t, c_char_p
 
-        buf = c_buffer(256)
+        buf = create_string_buffer(256)
         PyOS_snprintf(buf, sizeof(buf), b"Hello from %s", b"ctypes")
         self.assertEqual(buf.value, b"Hello from ctypes")
 
diff --git a/Lib/test/test_ctypes/test_random_things.py b/Lib/test/test_ctypes/test_random_things.py
index fcea8e847eb6..65eb53f86475 100644
--- a/Lib/test/test_ctypes/test_random_things.py
+++ b/Lib/test/test_ctypes/test_random_things.py
@@ -1,3 +1,4 @@
+import _ctypes
 import contextlib
 import ctypes
 import sys
@@ -10,14 +11,13 @@ def callback_func(arg):
     42 / arg
     raise ValueError(arg)
 
+
 @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test')
 class call_function_TestCase(unittest.TestCase):
     # _ctypes.call_function is deprecated and private, but used by
     # Gary Bishp's readline module.  If we have it, we must test it as well.
 
     def test(self):
-        from _ctypes import call_function
-
         kernel32 = ctypes.windll.kernel32
         kernel32.LoadLibraryA.restype = c_void_p
         kernel32.GetProcAddress.argtypes = c_void_p, c_char_p
@@ -26,9 +26,10 @@ def test(self):
         hdll = kernel32.LoadLibraryA(b"kernel32")
         funcaddr = kernel32.GetProcAddress(hdll, b"GetModuleHandleA")
 
-        self.assertEqual(call_function(funcaddr, (None,)),
+        self.assertEqual(_ctypes.call_function(funcaddr, (None,)),
                          kernel32.GetModuleHandleA(None))
 
+
 class CallbackTracbackTestCase(unittest.TestCase):
     # When an exception is raised in a ctypes callback function, the C
     # code prints a traceback.
diff --git a/Lib/test/test_ctypes/test_refcounts.py b/Lib/test/test_ctypes/test_refcounts.py
index b05cad0512c1..a1fe89105aee 100644
--- a/Lib/test/test_ctypes/test_refcounts.py
+++ b/Lib/test/test_ctypes/test_refcounts.py
@@ -1,17 +1,18 @@
+import _ctypes_test
 import ctypes
 import gc
 import sys
 import unittest
 from test import support
 
+
 MyCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)
 OtherCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong)
 
-import _ctypes_test
 dll = ctypes.CDLL(_ctypes_test.__file__)
 
-class RefcountTestCase(unittest.TestCase):
 
+class RefcountTestCase(unittest.TestCase):
     @support.refcount_test
     def test_1(self):
         f = dll._testfunc_callback_i_if
@@ -34,7 +35,6 @@ def callback(value):
 
         self.assertEqual(sys.getrefcount(callback), 2)
 
-
     @support.refcount_test
     def test_refcount(self):
         def func(*args):
@@ -82,10 +82,9 @@ class X(ctypes.Structure):
         gc.collect()
         self.assertEqual(sys.getrefcount(func), 2)
 
+
 class AnotherLeak(unittest.TestCase):
     def test_callback(self):
-        import sys
-
         proto = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int)
         def func(a, b):
             return a * b * 2
@@ -110,5 +109,6 @@ def func():
                 for _ in range(10000):
                     func()
 
+
 if __name__ == '__main__':
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_repr.py b/Lib/test/test_ctypes/test_repr.py
index bb6b5ae5e799..e7587984a92c 100644
--- a/Lib/test/test_ctypes/test_repr.py
+++ b/Lib/test/test_ctypes/test_repr.py
@@ -1,7 +1,8 @@
+import unittest
 from ctypes import (c_byte, c_short, c_int, c_long, c_longlong,
                     c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong,
                     c_float, c_double, c_longdouble, c_bool, c_char)
-import unittest
+
 
 subclasses = []
 for base in [c_byte, c_short, c_int, c_long, c_longlong,
@@ -11,11 +12,12 @@ class X(base):
         pass
     subclasses.append(X)
 
+
 class X(c_char):
     pass
 
-# This test checks if the __repr__ is correct for subclasses of simple types
 
+# This test checks if the __repr__ is correct for subclasses of simple types
 class ReprTest(unittest.TestCase):
     def test_numbers(self):
         for typ in subclasses:
diff --git a/Lib/test/test_ctypes/test_returnfuncptrs.py b/Lib/test/test_ctypes/test_returnfuncptrs.py
index 6a624133554e..4010e511e75a 100644
--- a/Lib/test/test_ctypes/test_returnfuncptrs.py
+++ b/Lib/test/test_ctypes/test_returnfuncptrs.py
@@ -1,10 +1,9 @@
+import _ctypes_test
 import unittest
 from ctypes import CDLL, CFUNCTYPE, ArgumentError, c_char_p, c_void_p, c_char
 
-import _ctypes_test
 
 class ReturnFuncPtrTestCase(unittest.TestCase):
-
     def test_with_prototype(self):
         # The _ctypes_test shared lib/dll exports quite some functions for testing.
         # The get_strchr function returns a *pointer* to the C strchr function.
diff --git a/Lib/test/test_ctypes/test_slicing.py b/Lib/test/test_ctypes/test_slicing.py
index 30db90cd7c0f..a592d911cbe6 100644
--- a/Lib/test/test_ctypes/test_slicing.py
+++ b/Lib/test/test_ctypes/test_slicing.py
@@ -1,8 +1,8 @@
+import _ctypes_test
 import unittest
 from ctypes import (CDLL, POINTER, sizeof,
                     c_byte, c_short, c_int, c_long, c_char, c_wchar, c_char_p)
 
-import _ctypes_test
 
 class SlicesTestCase(unittest.TestCase):
     def test_getslice_cint(self):
@@ -164,7 +164,6 @@ def test_wchar_ptr(self):
         self.assertEqual(res[len(s)-2:5:-7], tmpl[:5:-7])
         dll.my_free(res)
 
-################################################################
 
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_stringptr.py b/Lib/test/test_ctypes/test_stringptr.py
index 8bf04339d44b..67c61c6c3e17 100644
--- a/Lib/test/test_ctypes/test_stringptr.py
+++ b/Lib/test/test_ctypes/test_stringptr.py
@@ -1,14 +1,15 @@
-import unittest
+import _ctypes_test
 import sys
+import unittest
 from test import support
-from ctypes import CDLL, Structure, POINTER, c_buffer, c_char, c_char_p
+from ctypes import (CDLL, Structure, POINTER, create_string_buffer,
+                    c_char, c_char_p)
 
-import _ctypes_test
 
 lib = CDLL(_ctypes_test.__file__)
 
-class StringPtrTestCase(unittest.TestCase):
 
+class StringPtrTestCase(unittest.TestCase):
     @support.refcount_test
     def test__POINTER_c_char(self):
         class X(Structure):
@@ -17,13 +18,13 @@ class X(Structure):
 
         # NULL pointer access
         self.assertRaises(ValueError, getattr, x.str, "contents")
-        b = c_buffer(b"Hello, World")
+        b = create_string_buffer(b"Hello, World")
         self.assertEqual(sys.getrefcount(b), 2)
         x.str = b
         self.assertEqual(sys.getrefcount(b), 3)
 
         # POINTER(c_char) and Python string is NOT compatible
-        # POINTER(c_char) and c_buffer() is compatible
+        # POINTER(c_char) and create_string_buffer() is compatible
         for i in range(len(b)):
             self.assertEqual(b[i], x.str[i])
 
@@ -35,11 +36,11 @@ class X(Structure):
         x = X()
 
         # c_char_p and Python string is compatible
-        # c_char_p and c_buffer is NOT compatible
+        # c_char_p and create_string_buffer is NOT compatible
         self.assertEqual(x.str, None)
         x.str = b"Hello, World"
         self.assertEqual(x.str, b"Hello, World")
-        b = c_buffer(b"Hello, World")
+        b = create_string_buffer(b"Hello, World")
         self.assertRaises(TypeError, setattr, x, b"str", b)
 
 
@@ -48,15 +49,16 @@ def test_functions(self):
         strchr.restype = c_char_p
 
         # c_char_p and Python string is compatible
-        # c_char_p and c_buffer are now compatible
+        # c_char_p and create_string_buffer are now compatible
         strchr.argtypes = c_char_p, c_char
         self.assertEqual(strchr(b"abcdef", b"c"), b"cdef")
-        self.assertEqual(strchr(c_buffer(b"abcdef"), b"c"), b"cdef")
+        self.assertEqual(strchr(create_string_buffer(b"abcdef"), b"c"),
+                         b"cdef")
 
         # POINTER(c_char) and Python string is NOT compatible
-        # POINTER(c_char) and c_buffer() is compatible
+        # POINTER(c_char) and create_string_buffer() is compatible
         strchr.argtypes = POINTER(c_char), c_char
-        buf = c_buffer(b"abcdef")
+        buf = create_string_buffer(b"abcdef")
         self.assertEqual(strchr(buf, b"c"), b"cdef")
         self.assertEqual(strchr(b"abcdef", b"c"), b"cdef")
 
@@ -65,7 +67,7 @@ def test_functions(self):
         # So we must keep a reference to buf separately
 
         strchr.restype = POINTER(c_char)
-        buf = c_buffer(b"abcdef")
+        buf = create_string_buffer(b"abcdef")
         r = strchr(buf, b"c")
         x = r[0], r[1], r[2], r[3], r[4]
         self.assertEqual(x, (b"c", b"d", b"e", b"f", b"\000"))
@@ -73,5 +75,6 @@ def test_functions(self):
         # Because r is a pointer to memory that is freed after deleting buf,
         # the pointer is hanging and using it would reference freed memory.
 
+
 if __name__ == '__main__':
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_strings.py b/Lib/test/test_ctypes/test_strings.py
index f02d6077def1..26f036adfb75 100644
--- a/Lib/test/test_ctypes/test_strings.py
+++ b/Lib/test/test_ctypes/test_strings.py
@@ -1,5 +1,6 @@
 import unittest
-from ctypes import c_buffer, sizeof, byref, c_char, c_wchar
+from ctypes import create_string_buffer, sizeof, byref, c_char, c_wchar
+
 
 class StringArrayTestCase(unittest.TestCase):
     def test(self):
@@ -24,8 +25,8 @@ def test(self):
         self.assertRaises(ValueError, setattr, buf, "value", b"aaaaaaaa")
         self.assertRaises(TypeError, setattr, buf, "value", 42)
 
-    def test_c_buffer_value(self):
-        buf = c_buffer(32)
+    def test_create_string_buffer_value(self):
+        buf = create_string_buffer(32)
 
         buf.value = b"Hello, World"
         self.assertEqual(buf.value, b"Hello, World")
@@ -34,8 +35,8 @@ def test_c_buffer_value(self):
         self.assertRaises(TypeError, setattr, buf, "value", memoryview(b"abc"))
         self.assertRaises(ValueError, setattr, buf, "raw", memoryview(b"x" * 100))
 
-    def test_c_buffer_raw(self):
-        buf = c_buffer(32)
+    def test_create_string_buffer_raw(self):
+        buf = create_string_buffer(32)
 
         buf.raw = memoryview(b"Hello, World")
         self.assertEqual(buf.value, b"Hello, World")
@@ -90,7 +91,6 @@ def test_wchar(self):
         repr(byref(c_wchar("x")))
         c_wchar("x")
 
-
     @unittest.skip('test disabled')
     def test_basic_wstrings(self):
         cs = c_wstring("abcdef")
diff --git a/Lib/test/test_ctypes/test_struct_fields.py b/Lib/test/test_ctypes/test_struct_fields.py
index 17a2e69f76d9..f60dfe5b42ef 100644
--- a/Lib/test/test_ctypes/test_struct_fields.py
+++ b/Lib/test/test_ctypes/test_struct_fields.py
@@ -1,6 +1,7 @@
 import unittest
 from ctypes import Structure, Union, sizeof, c_char, c_int
 
+
 class StructFieldsTestCase(unittest.TestCase):
     # Structure/Union classes must get 'finalized' sooner or
     # later, when one of these things happen:
@@ -93,5 +94,6 @@ class MyCUnion(Union):
         self.assertRaises(TypeError,
                           MyCUnion.field.__get__, 'wrong type self', 42)
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_structures.py b/Lib/test/test_ctypes/test_structures.py
index 98099e8b8c08..e656d1893477 100644
--- a/Lib/test/test_ctypes/test_structures.py
+++ b/Lib/test/test_ctypes/test_structures.py
@@ -1,4 +1,6 @@
+import _ctypes_test
 import platform
+import struct
 import sys
 import unittest
 from ctypes import (CDLL, Structure, Union, POINTER, sizeof, byref, alignment,
@@ -7,14 +9,15 @@
                     c_short, c_ushort, c_int, c_uint,
                     c_long, c_ulong, c_longlong, c_ulonglong, c_float, c_double)
 from struct import calcsize
-import _ctypes_test
 from test import support
 
+
 # The following definition is meant to be used from time to time to assist
 # temporarily disabling tests on specific architectures while investigations
 # are in progress, to keep buildbots happy.
 MACHINE = platform.machine()
 
+
 class SubclassesTest(unittest.TestCase):
     def test_subclass(self):
         class X(Structure):
@@ -54,6 +57,7 @@ class Z(X):
         self.assertEqual(Y._fields_, [("b", c_int)])
         self.assertEqual(Z._fields_, [("a", c_int)])
 
+
 class StructureTestCase(unittest.TestCase):
     formats = {"c": c_char,
                "b": c_byte,
@@ -187,7 +191,6 @@ class X(Structure):
         self.assertEqual(sizeof(X), 10)
         self.assertEqual(X.b.offset, 2)
 
-        import struct
         longlong_size = struct.calcsize("q")
         longlong_align = struct.calcsize("bq") - longlong_size
 
@@ -740,6 +743,7 @@ class Test8(Union):
         self.assertEqual(ctx.exception.args[0], 'item 1 in _argtypes_ passes '
                          'a union by value, which is unsupported.')
 
+
 class PointerMemberTestCase(unittest.TestCase):
 
     def test(self):
@@ -781,6 +785,7 @@ class S(Structure):
         s.p = None
         self.assertEqual(s.x, 12345678)
 
+
 class TestRecursiveStructure(unittest.TestCase):
     def test_contains_itself(self):
         class Recursive(Structure):
@@ -810,5 +815,6 @@ class Second(Structure):
         else:
             self.fail("AttributeError not raised")
 
+
 if __name__ == '__main__':
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_unaligned_structures.py b/Lib/test/test_ctypes/test_unaligned_structures.py
index a7e1796d4d63..58a00597ef5c 100644
--- a/Lib/test/test_ctypes/test_unaligned_structures.py
+++ b/Lib/test/test_ctypes/test_unaligned_structures.py
@@ -4,6 +4,7 @@
                     c_float, c_double,
                     c_ushort, c_uint, c_ulong, c_ulonglong)
 
+
 structures = []
 byteswapped_structures = []
 
@@ -27,6 +28,7 @@ class Y(SwappedStructure):
     structures.append(X)
     byteswapped_structures.append(Y)
 
+
 class TestStructures(unittest.TestCase):
     def test_native(self):
         for typ in structures:
@@ -42,5 +44,6 @@ def test_swapped(self):
             o.value = 4
             self.assertEqual(o.value, 4)
 
+
 if __name__ == '__main__':
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_unicode.py b/Lib/test/test_ctypes/test_unicode.py
index fe8a157f3c60..2ddc7c56544e 100644
--- a/Lib/test/test_ctypes/test_unicode.py
+++ b/Lib/test/test_ctypes/test_unicode.py
@@ -1,7 +1,7 @@
-import unittest
+import _ctypes_test
 import ctypes
+import unittest
 
-import _ctypes_test
 
 class UnicodeTestCase(unittest.TestCase):
     def test_wcslen(self):
diff --git a/Lib/test/test_ctypes/test_values.py b/Lib/test/test_ctypes/test_values.py
index 9707e032dc37..9f8b69409cb8 100644
--- a/Lib/test/test_ctypes/test_values.py
+++ b/Lib/test/test_ctypes/test_values.py
@@ -2,14 +2,16 @@
 A testcase which accesses *values* in a dll.
 """
 
+import _ctypes_test
 import _imp
 import importlib.util
-import unittest
 import sys
-from ctypes import Structure, CDLL, POINTER, pythonapi, c_ubyte, c_char_p, c_int
+import unittest
+from ctypes import (Structure, CDLL, POINTER, pythonapi,
+                    _pointer_type_cache,
+                    c_ubyte, c_char_p, c_int)
 from test.support import import_helper
 
-import _ctypes_test
 
 class ValuesTestCase(unittest.TestCase):
 
@@ -31,6 +33,7 @@ def test_undefined(self):
         ctdll = CDLL(_ctypes_test.__file__)
         self.assertRaises(ValueError, c_int.in_dll, ctdll, "Undefined_Symbol")
 
+
 class PythonValuesTestCase(unittest.TestCase):
     """This test only works when python itself is a dll/shared library"""
 
@@ -92,12 +95,12 @@ class struct_frozen(Structure):
                          "_PyImport_FrozenBootstrap example "
                          "in Doc/library/ctypes.rst may be out of date")
 
-        from ctypes import _pointer_type_cache
         del _pointer_type_cache[struct_frozen]
 
     def test_undefined(self):
         self.assertRaises(ValueError, c_int.in_dll, pythonapi,
                           "Undefined_Symbol")
 
+
 if __name__ == '__main__':
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_varsize_struct.py b/Lib/test/test_ctypes/test_varsize_struct.py
index d2fa0b36c785..3e6ba6fed07e 100644
--- a/Lib/test/test_ctypes/test_varsize_struct.py
+++ b/Lib/test/test_ctypes/test_varsize_struct.py
@@ -1,5 +1,6 @@
-from ctypes import Structure, sizeof, resize, c_int
 import unittest
+from ctypes import Structure, sizeof, resize, c_int
+
 
 class VarSizeTest(unittest.TestCase):
     def test_resize(self):
@@ -46,5 +47,6 @@ def test_zerosized_array(self):
         self.assertRaises(IndexError, array.__setitem__, -1, None)
         self.assertRaises(IndexError, array.__getitem__, -1)
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/Lib/test/test_ctypes/test_win32.py b/Lib/test/test_ctypes/test_win32.py
index a8987dd1da68..01e624f76f06 100644
--- a/Lib/test/test_ctypes/test_win32.py
+++ b/Lib/test/test_ctypes/test_win32.py
@@ -2,9 +2,11 @@
 
 import _ctypes_test
 import ctypes
+import errno
 import sys
 import unittest
 from ctypes import (CDLL, Structure, POINTER, pointer, sizeof, byref,
+                    _pointer_type_cache,
                     c_void_p, c_char, c_int, c_long)
 from test import support
 
@@ -47,7 +49,6 @@ class S(Structure):
                 self.assertEqual(value, expected)
 
 
-
 @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test')
 class TestWintypes(unittest.TestCase):
     def test_HWND(self):
@@ -72,11 +73,11 @@ def test_COMError(self):
         self.assertEqual(ex.text, "text")
         self.assertEqual(ex.details, ("details",))
 
+
 @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test')
 class TestWinError(unittest.TestCase):
     def test_winerror(self):
         # see Issue 16169
-        import errno
         ERROR_INVALID_PARAMETER = 87
         msg = ctypes.FormatError(ERROR_INVALID_PARAMETER).strip()
         args = (errno.EINVAL, msg, None, ERROR_INVALID_PARAMETER)
@@ -136,7 +137,6 @@ class RECT(Structure):
             self.assertEqual(ret.bottom, bottom.value)
 
         # to not leak references, we must clean _pointer_type_cache
-        from ctypes import _pointer_type_cache
         del _pointer_type_cache[RECT]
 
 
diff --git a/Lib/test/test_ctypes/test_wintypes.py b/Lib/test/test_ctypes/test_wintypes.py
index 66fb8b78545a..a04d725a4739 100644
--- a/Lib/test/test_ctypes/test_wintypes.py
+++ b/Lib/test/test_ctypes/test_wintypes.py
@@ -1,10 +1,9 @@
 # See <https://learn.microsoft.com/en-us/windows/win32/winprog/windows-data-types>
 # for reference.
+#
+# Tests also work on POSIX
 
 import unittest
-
-# also work on POSIX
-
 from ctypes import POINTER, cast, c_int16
 from ctypes import wintypes
 



More information about the Python-checkins mailing list