From 705ba8349b9eed485a131b0c62980a2f6267e15e Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Sun, 14 Jun 2020 13:52:56 +0200 Subject: [PATCH 1/8] Drop Python 2 support --- .travis.yml | 1 - CHANGELOG.md | 1 + appveyor.yml | 5 +- setup.py | 13 +- src/clrmodule/ClrModule.cs | 13 -- src/embed_tests/TestCallbacks.cs | 4 +- src/runtime/CustomMarshaler.cs | 8 +- src/runtime/Python.Runtime.csproj | 371 +++++++++++++++--------------- src/runtime/converter.cs | 113 ++------- src/runtime/delegateobject.cs | 9 - src/runtime/exceptions.cs | 7 +- src/runtime/importhook.cs | 16 -- src/runtime/interop.cs | 37 --- src/runtime/interop27.cs | 150 ------------ src/runtime/pythonengine.cs | 20 +- src/runtime/runtime.cs | 173 +------------- src/runtime/typemanager.cs | 11 - 17 files changed, 222 insertions(+), 730 deletions(-) delete mode 100644 src/runtime/interop27.cs diff --git a/.travis.yml b/.travis.yml index 2062a35da..5a2c975eb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,7 +6,6 @@ python: - 3.7 - 3.6 - 3.5 - - 2.7 env: matrix: diff --git a/CHANGELOG.md b/CHANGELOG.md index 24dd3ce45..3e82f40e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. ### Added ### Changed +- Drop support for Python 2 ### Fixed diff --git a/appveyor.yml b/appveyor.yml index b58b72372..d353bbe5f 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -3,7 +3,7 @@ build: off image: - Visual Studio 2017 - + platform: - x86 - x64 @@ -23,13 +23,10 @@ environment: BUILD_OPTS: --xplat - PYTHON_VERSION: 3.5 BUILD_OPTS: --xplat - - PYTHON_VERSION: 2.7 - BUILD_OPTS: --xplat - PYTHON_VERSION: 3.8 - PYTHON_VERSION: 3.7 - PYTHON_VERSION: 3.6 - PYTHON_VERSION: 3.5 - - PYTHON_VERSION: 2.7 init: # Update Environment Variables based on matrix/platform diff --git a/setup.py b/setup.py index bab771b08..9d21c7038 100644 --- a/setup.py +++ b/setup.py @@ -255,17 +255,11 @@ def build_extension(self, ext): # Up to Python 3.2 sys.maxunicode is used to determine the size of # Py_UNICODE, but from 3.3 onwards Py_UNICODE is a typedef of wchar_t. - # TODO: Is this doing the right check for Py27? - if sys.version_info[:2] <= (3, 2): - unicode_width = 2 if sys.maxunicode < 0x10FFFF else 4 - else: - import ctypes - - unicode_width = ctypes.sizeof(ctypes.c_wchar) + import ctypes + unicode_width = ctypes.sizeof(ctypes.c_wchar) defines = [ "PYTHON{0}{1}".format(PY_MAJOR, PY_MINOR), - "PYTHON{0}".format(PY_MAJOR), # Python Major Version "UCS{0}".format(unicode_width), ] @@ -274,7 +268,6 @@ def build_extension(self, ext): if sys.platform != "win32" and (DEVTOOLS == "Mono" or DEVTOOLS == "dotnet"): on_darwin = sys.platform == "darwin" - defines.append("MONO_OSX" if on_darwin else "MONO_LINUX") # Check if --enable-shared was set when Python was built enable_shared = sysconfig.get_config_var("Py_ENABLE_SHARED") @@ -645,8 +638,6 @@ def run(self): "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: C#", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", diff --git a/src/clrmodule/ClrModule.cs b/src/clrmodule/ClrModule.cs index 377be66d1..e19e58594 100644 --- a/src/clrmodule/ClrModule.cs +++ b/src/clrmodule/ClrModule.cs @@ -30,13 +30,8 @@ public class clrModule { -#if PYTHON3 [DllExport("PyInit_clr", CallingConvention.StdCall)] public static IntPtr PyInit_clr() -#elif PYTHON2 - [DllExport("initclr", CallingConvention.StdCall)] - public static void initclr() -#endif { DebugPrint("Attempting to load 'Python.Runtime' using standard binding rules."); #if USE_PYTHON_RUNTIME_PUBLIC_KEY_TOKEN @@ -95,11 +90,7 @@ public static void initclr() catch (InvalidOperationException) { DebugPrint("Could not load 'Python.Runtime'."); -#if PYTHON3 return IntPtr.Zero; -#elif PYTHON2 - return; -#endif } } @@ -107,11 +98,7 @@ public static void initclr() // So now we get the PythonEngine and execute the InitExt method on it. Type pythonEngineType = pythonRuntime.GetType("Python.Runtime.PythonEngine"); -#if PYTHON3 return (IntPtr)pythonEngineType.InvokeMember("InitExt", BindingFlags.InvokeMethod, null, null, null); -#elif PYTHON2 - pythonEngineType.InvokeMember("InitExt", BindingFlags.InvokeMethod, null, null, null); -#endif } /// diff --git a/src/embed_tests/TestCallbacks.cs b/src/embed_tests/TestCallbacks.cs index 220b0a86a..454c97578 100644 --- a/src/embed_tests/TestCallbacks.cs +++ b/src/embed_tests/TestCallbacks.cs @@ -25,9 +25,7 @@ public void TestNoOverloadException() { dynamic callWith42 = PythonEngine.Eval("lambda f: f([42])"); var error = Assert.Throws(() => callWith42(aFunctionThatCallsIntoPython.ToPython())); Assert.AreEqual("TypeError", error.PythonTypeName); - string expectedArgTypes = Runtime.IsPython2 - ? "()" - : "()"; + string expectedArgTypes = "()"; StringAssert.EndsWith(expectedArgTypes, error.Message); } } diff --git a/src/runtime/CustomMarshaler.cs b/src/runtime/CustomMarshaler.cs index b51911816..0cbbbaba2 100644 --- a/src/runtime/CustomMarshaler.cs +++ b/src/runtime/CustomMarshaler.cs @@ -120,9 +120,7 @@ public static int GetUnicodeByteLength(IntPtr p) /// public static IntPtr Py3UnicodePy2StringtoPtr(string s) { - return Runtime.IsPython3 - ? Instance.MarshalManagedToNative(s) - : Marshal.StringToHGlobalAnsi(s); + return Instance.MarshalManagedToNative(s); } /// @@ -137,9 +135,7 @@ public static IntPtr Py3UnicodePy2StringtoPtr(string s) /// public static string PtrToPy3UnicodePy2String(IntPtr p) { - return Runtime.IsPython3 - ? PtrToStringUni(p) - : Marshal.PtrToStringAnsi(p); + return PtrToStringUni(p); } } diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index 75f5e2fab..1fd1d991e 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -1,186 +1,185 @@ - - - - Debug - AnyCPU - {097B4AC0-74E9-4C58-BCF8-C69746EC8271} - Library - Python.Runtime - Python.Runtime - bin\Python.Runtime.xml - bin\ - v4.0 - - 1591 - ..\..\ - $(SolutionDir)\bin\ - Properties - 7.3 - true - false - ..\pythonnet.snk - - - - - - PYTHON2;PYTHON27;UCS4 - true - pdbonly - - - PYTHON3;PYTHON38;UCS4 - true - pdbonly - - - true - PYTHON2;PYTHON27;UCS4;TRACE;DEBUG - false - full - - - true - PYTHON3;PYTHON38;UCS4;TRACE;DEBUG - false - full - - - PYTHON2;PYTHON27;UCS2 - true - pdbonly - - - PYTHON3;PYTHON38;UCS2 - true - pdbonly - - - true - PYTHON2;PYTHON27;UCS2;TRACE;DEBUG - false - full - - - true - PYTHON3;PYTHON38;UCS2;TRACE;DEBUG - false - full - - - - - - - - - - - - - - Properties\SharedAssemblyInfo.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - clr.py - - - - - $(TargetPath) - $(TargetDir)$(TargetName).pdb - - - - - - \ No newline at end of file + + + + Debug + AnyCPU + {097B4AC0-74E9-4C58-BCF8-C69746EC8271} + Library + Python.Runtime + Python.Runtime + bin\Python.Runtime.xml + bin\ + v4.0 + + 1591 + ..\..\ + $(SolutionDir)\bin\ + Properties + 7.3 + true + false + ..\pythonnet.snk + + + + + + PYTHON2;PYTHON27;UCS4 + true + pdbonly + + + PYTHON3;PYTHON38;UCS4 + true + pdbonly + + + true + PYTHON2;PYTHON27;UCS4;TRACE;DEBUG + false + full + + + true + PYTHON3;PYTHON38;UCS4;TRACE;DEBUG + false + full + + + PYTHON2;PYTHON27;UCS2 + true + pdbonly + + + PYTHON3;PYTHON38;UCS2 + true + pdbonly + + + true + PYTHON2;PYTHON27;UCS2;TRACE;DEBUG + false + full + + + true + PYTHON3;PYTHON38;UCS2;TRACE;DEBUG + false + full + + + + + + + + + + + + + + Properties\SharedAssemblyInfo.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + clr.py + + + + + $(TargetPath) + $(TargetDir)$(TargetName).pdb + + + + + + diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index 3add8aba0..2b92ca994 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -86,9 +86,6 @@ internal static IntPtr GetPythonTypeByAlias(Type op) if (op == int32Type) return Runtime.PyIntType; - if (op == int64Type && Runtime.IsPython2) - return Runtime.PyLongType; - if (op == int64Type) return Runtime.PyIntType; @@ -488,63 +485,35 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo return true; case TypeCode.Int32: - // Trickery to support 64-bit platforms. - if (Runtime.IsPython2 && Runtime.Is32Bit) + // Python3 always use PyLong API + op = Runtime.PyNumber_Long(value); + if (op == IntPtr.Zero) { - op = Runtime.PyNumber_Int(value); - - // As of Python 2.3, large ints magically convert :( - if (Runtime.PyLong_Check(op)) + Exceptions.Clear(); + if (Exceptions.ExceptionMatches(overflow)) { - Runtime.XDecref(op); goto overflow; } - - if (op == IntPtr.Zero) - { - if (Exceptions.ExceptionMatches(overflow)) - { - goto overflow; - } - goto type_error; - } - ival = (int)Runtime.PyInt_AsLong(op); - Runtime.XDecref(op); - result = ival; - return true; + goto type_error; } - else // Python3 always use PyLong API + long ll = (long)Runtime.PyLong_AsLongLong(op); + Runtime.XDecref(op); + if (ll == -1 && Exceptions.ErrorOccurred()) { - op = Runtime.PyNumber_Long(value); - if (op == IntPtr.Zero) - { - Exceptions.Clear(); - if (Exceptions.ExceptionMatches(overflow)) - { - goto overflow; - } - goto type_error; - } - long ll = (long)Runtime.PyLong_AsLongLong(op); - Runtime.XDecref(op); - if (ll == -1 && Exceptions.ErrorOccurred()) - { - goto overflow; - } - if (ll > Int32.MaxValue || ll < Int32.MinValue) - { - goto overflow; - } - result = (int)ll; - return true; + goto overflow; } + if (ll > Int32.MaxValue || ll < Int32.MinValue) + { + goto overflow; + } + result = (int)ll; + return true; case TypeCode.Boolean: result = Runtime.PyObject_IsTrue(value) != 0; return true; case TypeCode.Byte: -#if PYTHON3 if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) { if (Runtime.PyBytes_Size(value) == 1) @@ -555,18 +524,6 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo } goto type_error; } -#elif PYTHON2 - if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType)) - { - if (Runtime.PyString_Size(value) == 1) - { - op = Runtime.PyString_AsString(value); - result = (byte)Marshal.ReadByte(op); - return true; - } - goto type_error; - } -#endif op = Runtime.PyNumber_Int(value); if (op == IntPtr.Zero) @@ -589,7 +546,6 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo return true; case TypeCode.SByte: -#if PYTHON3 if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) { if (Runtime.PyBytes_Size(value) == 1) @@ -600,18 +556,6 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo } goto type_error; } -#elif PYTHON2 - if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType)) - { - if (Runtime.PyString_Size(value) == 1) - { - op = Runtime.PyString_AsString(value); - result = (sbyte)Marshal.ReadByte(op); - return true; - } - goto type_error; - } -#endif op = Runtime.PyNumber_Int(value); if (op == IntPtr.Zero) @@ -634,7 +578,6 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo return true; case TypeCode.Char: -#if PYTHON3 if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) { if (Runtime.PyBytes_Size(value) == 1) @@ -645,18 +588,6 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo } goto type_error; } -#elif PYTHON2 - if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType)) - { - if (Runtime.PyString_Size(value) == 1) - { - op = Runtime.PyString_AsString(value); - result = (char)Marshal.ReadByte(op); - return true; - } - goto type_error; - } -#endif else if (Runtime.PyObject_TypeCheck(value, Runtime.PyUnicodeType)) { if (Runtime.PyUnicode_GetSize(value) == 1) @@ -753,20 +684,20 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo } goto type_error; } - + uint ui; - try + try { ui = Convert.ToUInt32(Runtime.PyLong_AsUnsignedLong(op)); } catch (OverflowException) { // Probably wasn't an overflow in python but was in C# (e.g. if cpython - // longs are 64 bit then 0xFFFFFFFF + 1 will not overflow in + // longs are 64 bit then 0xFFFFFFFF + 1 will not overflow in // PyLong_AsUnsignedLong) Runtime.XDecref(op); goto overflow; } - + if (Exceptions.ErrorOccurred()) { @@ -900,7 +831,7 @@ private static bool ToArray(IntPtr value, Type obType, out object result, bool s var listType = typeof(List<>); var constructedListType = listType.MakeGenericType(elementType); - IList list = IsSeqObj ? (IList) Activator.CreateInstance(constructedListType, new Object[] {(int) len}) : + IList list = IsSeqObj ? (IList) Activator.CreateInstance(constructedListType, new Object[] {(int) len}) : (IList) Activator.CreateInstance(constructedListType); IntPtr item; @@ -921,7 +852,7 @@ private static bool ToArray(IntPtr value, Type obType, out object result, bool s items = Array.CreateInstance(elementType, list.Count); list.CopyTo(items, 0); - + result = items; return true; } diff --git a/src/runtime/delegateobject.cs b/src/runtime/delegateobject.cs index e1103cbc7..c9aad9898 100644 --- a/src/runtime/delegateobject.cs +++ b/src/runtime/delegateobject.cs @@ -96,7 +96,6 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) /// /// Implements __cmp__ for reflected delegate types. /// -#if PYTHON3 // TODO: Doesn't PY2 implement tp_richcompare too? public new static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) { if (op != Runtime.Py_EQ && op != Runtime.Py_NE) @@ -126,13 +125,5 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) Runtime.XIncref(pyfalse); return pyfalse; } -#elif PYTHON2 - public static int tp_compare(IntPtr ob, IntPtr other) - { - Delegate d1 = GetTrueDelegate(ob); - Delegate d2 = GetTrueDelegate(other); - return d1 == d2 ? 0 : -1; - } -#endif } } diff --git a/src/runtime/exceptions.cs b/src/runtime/exceptions.cs index 31c367eb2..e5efecbcf 100644 --- a/src/runtime/exceptions.cs +++ b/src/runtime/exceptions.cs @@ -103,7 +103,7 @@ private Exceptions() /// internal static void Initialize() { - string exceptionsModuleName = Runtime.IsPython3 ? "builtins" : "exceptions"; + string exceptionsModuleName = "builtins"; exceptions_module = Runtime.PyImport_ImportModule(exceptionsModuleName); Exceptions.ErrorCheck(exceptions_module); @@ -180,13 +180,11 @@ internal static void SetArgsAndCause(IntPtr ob) Marshal.WriteIntPtr(ob, ExceptionOffset.args, args); -#if PYTHON3 if (e.InnerException != null) { IntPtr cause = CLRObject.GetInstHandle(e.InnerException); Marshal.WriteIntPtr(ob, ExceptionOffset.cause, cause); } -#endif } /// @@ -386,9 +384,6 @@ puplic static variables on the Exceptions class filled in from public static IntPtr Exception; public static IntPtr StopIteration; public static IntPtr GeneratorExit; -#if PYTHON2 - public static IntPtr StandardError; -#endif public static IntPtr ArithmeticError; public static IntPtr LookupError; diff --git a/src/runtime/importhook.cs b/src/runtime/importhook.cs index aa3bbab6d..4c797ff8d 100644 --- a/src/runtime/importhook.cs +++ b/src/runtime/importhook.cs @@ -13,7 +13,6 @@ internal class ImportHook private static MethodWrapper hook; private static IntPtr py_clr_module; -#if PYTHON3 private static IntPtr module_def = IntPtr.Zero; internal static void InitializeModuleDef() @@ -33,7 +32,6 @@ internal static void ReleaseModuleDef() ModuleDefOffset.FreeModuleDef(module_def); module_def = IntPtr.Zero; } -#endif /// /// Initialize just the __import__ hook itself. @@ -82,7 +80,6 @@ internal static void Initialize() // Initialize the clr module and tell Python about it. root = new CLRModule(); -#if PYTHON3 // create a python module with the same methods as the clr module-like object InitializeModuleDef(); py_clr_module = Runtime.PyModule_Create2(module_def, 3); @@ -93,10 +90,6 @@ internal static void Initialize() clr_dict = (IntPtr)Marshal.PtrToStructure(clr_dict, typeof(IntPtr)); Runtime.PyDict_Update(mod_dict, clr_dict); -#elif PYTHON2 - Runtime.XIncref(root.pyHandle); // we are using the module two times - py_clr_module = root.pyHandle; // Alias handle for PY2/PY3 -#endif IntPtr dict = Runtime.PyImport_GetModuleDict(); Runtime.PyDict_SetItemString(dict, "CLR", py_clr_module); Runtime.PyDict_SetItemString(dict, "clr", py_clr_module); @@ -118,12 +111,10 @@ internal static void Shutdown() bool shouldFreeDef = Runtime.Refcount(py_clr_module) == 1; Runtime.XDecref(py_clr_module); py_clr_module = IntPtr.Zero; -#if PYTHON3 if (shouldFreeDef) { ReleaseModuleDef(); } -#endif Runtime.XDecref(root.pyHandle); root = null; @@ -137,13 +128,6 @@ public static IntPtr GetCLRModule(IntPtr? fromList = null) { root.InitializePreload(); - if (Runtime.IsPython2) - { - Runtime.XIncref(py_clr_module); - return py_clr_module; - } - - // Python 3 // update the module dictionary with the contents of the root dictionary root.LoadNames(); IntPtr py_mod_dict = Runtime.PyModule_GetDict(py_clr_module); diff --git a/src/runtime/interop.cs b/src/runtime/interop.cs index 039feddc7..95f3e5b9f 100644 --- a/src/runtime/interop.cs +++ b/src/runtime/interop.cs @@ -212,20 +212,15 @@ static ExceptionOffset() // (start after PyObject_HEAD) public static int dict = 0; public static int args = 0; -#if PYTHON2 - public static int message = 0; -#elif PYTHON3 public static int traceback = 0; public static int context = 0; public static int cause = 0; public static int suppress_context = 0; -#endif private static readonly int size; } -#if PYTHON3 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal class BytesOffset { @@ -316,7 +311,6 @@ public static void FreeModuleDef(IntPtr ptr) public static int name = 0; } -#endif // PYTHON3 /// /// TypeFlags(): The actual bit values for the Type Flags stored @@ -326,17 +320,6 @@ public static void FreeModuleDef(IntPtr ptr) /// internal class TypeFlags { -#if PYTHON2 // these flags were removed in Python 3 - public static int HaveGetCharBuffer = (1 << 0); - public static int HaveSequenceIn = (1 << 1); - public static int GC = 0; - public static int HaveInPlaceOps = (1 << 3); - public static int CheckTypes = (1 << 4); - public static int HaveRichCompare = (1 << 5); - public static int HaveWeakRefs = (1 << 6); - public static int HaveIter = (1 << 7); - public static int HaveClass = (1 << 8); -#endif public static int HeapType = (1 << 9); public static int BaseType = (1 << 10); public static int Ready = (1 << 12); @@ -364,23 +347,9 @@ internal class TypeFlags public static int BaseExceptionSubclass = (1 << 30); public static int TypeSubclass = (1 << 31); -#if PYTHON2 // Default flags for Python 2 - public static int Default = ( - HaveGetCharBuffer | - HaveSequenceIn | - HaveInPlaceOps | - HaveRichCompare | - HaveWeakRefs | - HaveIter | - HaveClass | - HaveStacklessExtension | - HaveIndex | - 0); -#elif PYTHON3 // Default flags for Python 3 public static int Default = ( HaveStacklessExtension | HaveVersionTag); -#endif } @@ -438,9 +407,6 @@ static Interop() pmap["nb_add"] = p["BinaryFunc"]; pmap["nb_subtract"] = p["BinaryFunc"]; pmap["nb_multiply"] = p["BinaryFunc"]; -#if PYTHON2 - pmap["nb_divide"] = p["BinaryFunc"]; -#endif pmap["nb_remainder"] = p["BinaryFunc"]; pmap["nb_divmod"] = p["BinaryFunc"]; pmap["nb_power"] = p["TernaryFunc"]; @@ -463,9 +429,6 @@ static Interop() pmap["nb_inplace_add"] = p["BinaryFunc"]; pmap["nb_inplace_subtract"] = p["BinaryFunc"]; pmap["nb_inplace_multiply"] = p["BinaryFunc"]; -#if PYTHON2 - pmap["nb_inplace_divide"] = p["BinaryFunc"]; -#endif pmap["nb_inplace_remainder"] = p["BinaryFunc"]; pmap["nb_inplace_power"] = p["TernaryFunc"]; pmap["nb_inplace_lshift"] = p["BinaryFunc"]; diff --git a/src/runtime/interop27.cs b/src/runtime/interop27.cs deleted file mode 100644 index 4782e9d3b..000000000 --- a/src/runtime/interop27.cs +++ /dev/null @@ -1,150 +0,0 @@ -// Auto-generated by geninterop.py. -// DO NOT MODIFIY BY HAND. - - -#if PYTHON27 -using System; -using System.Collections; -using System.Collections.Specialized; -using System.Runtime.InteropServices; -using System.Reflection; -using System.Text; - -namespace Python.Runtime -{ - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] - internal class TypeOffset - { - static TypeOffset() - { - Type type = typeof(TypeOffset); - FieldInfo[] fi = type.GetFields(); - int size = IntPtr.Size; - for (int i = 0; i < fi.Length; i++) - { - fi[i].SetValue(null, i * size); - } - } - - public static int magic() - { - return ob_size; - } - - // Auto-generated from PyHeapTypeObject in Python.h - public static int ob_refcnt = 0; - public static int ob_type = 0; - public static int ob_size = 0; - public static int tp_name = 0; - public static int tp_basicsize = 0; - public static int tp_itemsize = 0; - public static int tp_dealloc = 0; - public static int tp_print = 0; - public static int tp_getattr = 0; - public static int tp_setattr = 0; - public static int tp_compare = 0; - public static int tp_repr = 0; - public static int tp_as_number = 0; - public static int tp_as_sequence = 0; - public static int tp_as_mapping = 0; - public static int tp_hash = 0; - public static int tp_call = 0; - public static int tp_str = 0; - public static int tp_getattro = 0; - public static int tp_setattro = 0; - public static int tp_as_buffer = 0; - public static int tp_flags = 0; - public static int tp_doc = 0; - public static int tp_traverse = 0; - public static int tp_clear = 0; - public static int tp_richcompare = 0; - public static int tp_weaklistoffset = 0; - public static int tp_iter = 0; - public static int tp_iternext = 0; - public static int tp_methods = 0; - public static int tp_members = 0; - public static int tp_getset = 0; - public static int tp_base = 0; - public static int tp_dict = 0; - public static int tp_descr_get = 0; - public static int tp_descr_set = 0; - public static int tp_dictoffset = 0; - public static int tp_init = 0; - public static int tp_alloc = 0; - public static int tp_new = 0; - public static int tp_free = 0; - public static int tp_is_gc = 0; - public static int tp_bases = 0; - public static int tp_mro = 0; - public static int tp_cache = 0; - public static int tp_subclasses = 0; - public static int tp_weaklist = 0; - public static int tp_del = 0; - public static int tp_version_tag = 0; - public static int nb_add = 0; - public static int nb_subtract = 0; - public static int nb_multiply = 0; - public static int nb_divide = 0; - public static int nb_remainder = 0; - public static int nb_divmod = 0; - public static int nb_power = 0; - public static int nb_negative = 0; - public static int nb_positive = 0; - public static int nb_absolute = 0; - public static int nb_nonzero = 0; - public static int nb_invert = 0; - public static int nb_lshift = 0; - public static int nb_rshift = 0; - public static int nb_and = 0; - public static int nb_xor = 0; - public static int nb_or = 0; - public static int nb_coerce = 0; - public static int nb_int = 0; - public static int nb_long = 0; - public static int nb_float = 0; - public static int nb_oct = 0; - public static int nb_hex = 0; - public static int nb_inplace_add = 0; - public static int nb_inplace_subtract = 0; - public static int nb_inplace_multiply = 0; - public static int nb_inplace_divide = 0; - public static int nb_inplace_remainder = 0; - public static int nb_inplace_power = 0; - public static int nb_inplace_lshift = 0; - public static int nb_inplace_rshift = 0; - public static int nb_inplace_and = 0; - public static int nb_inplace_xor = 0; - public static int nb_inplace_or = 0; - public static int nb_floor_divide = 0; - public static int nb_true_divide = 0; - public static int nb_inplace_floor_divide = 0; - public static int nb_inplace_true_divide = 0; - public static int nb_index = 0; - public static int mp_length = 0; - public static int mp_subscript = 0; - public static int mp_ass_subscript = 0; - public static int sq_length = 0; - public static int sq_concat = 0; - public static int sq_repeat = 0; - public static int sq_item = 0; - public static int sq_slice = 0; - public static int sq_ass_item = 0; - public static int sq_ass_slice = 0; - public static int sq_contains = 0; - public static int sq_inplace_concat = 0; - public static int sq_inplace_repeat = 0; - public static int bf_getreadbuffer = 0; - public static int bf_getwritebuffer = 0; - public static int bf_getsegcount = 0; - public static int bf_getcharbuffer = 0; - public static int bf_getbuffer = 0; - public static int bf_releasebuffer = 0; - public static int name = 0; - public static int ht_slots = 0; - - /* here are optional user slots, followed by the members. */ - public static int members = 0; - } -} - -#endif diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index 11fc88cd4..4f77bec1d 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -96,10 +96,6 @@ public static string PythonPath } set { - if (Runtime.IsPython2) - { - throw new NotSupportedException("Set PythonPath not supported on Python 2"); - } Marshal.FreeHGlobal(_pythonPath); _pythonPath = UcsMarshaler.Py3UnicodePy2StringtoPtr(value); Runtime.Py_SetPath(_pythonPath); @@ -255,11 +251,7 @@ static void OnDomainUnload(object _, EventArgs __) /// CPython interpreter process - this bootstraps the managed runtime /// when it is imported by the CLR extension module. /// -#if PYTHON3 public static IntPtr InitExt() -#elif PYTHON2 - public static void InitExt() -#endif { try { @@ -299,14 +291,10 @@ public static void InitExt() catch (PythonException e) { e.Restore(); -#if PYTHON3 return IntPtr.Zero; -#endif } -#if PYTHON3 return Python.Runtime.ImportHook.GetCLRModule(); -#endif } /// @@ -322,7 +310,7 @@ public static void Shutdown() if (initialized) { PyScopeManager.Global.Clear(); - + // If the shutdown handlers trigger a domain unload, // don't call shutdown again. AppDomain.CurrentDomain.DomainUnload -= OnDomainUnload; @@ -588,7 +576,7 @@ internal static PyObject RunString(string code, IntPtr? globals, IntPtr? locals, borrowedGlobals = false; } } - + if (locals == null) { locals = globals; @@ -651,7 +639,7 @@ public static PyScope CreateScope(string name) var scope = PyScopeManager.Global.Create(name); return scope; } - + public class GILState : IDisposable { private readonly IntPtr state; @@ -752,7 +740,7 @@ public static void SetArgv(IEnumerable argv) public static void With(PyObject obj, Action Body) { - // Behavior described here: + // Behavior described here: // https://docs.python.org/2/reference/datamodel.html#with-statement-context-managers IntPtr type = Runtime.PyNone; diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 8cf24ba70..84f5a997e 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -50,10 +50,7 @@ public class Runtime public static string pyversion => _pyversion; public static string pyver => _pyver; -#if PYTHON27 - internal const string _pyversion = "2.7"; - internal const string _pyver = "27"; -#elif PYTHON34 +#if PYTHON34 internal const string _pyversion = "3.4"; internal const string _pyver = "34"; #elif PYTHON35 @@ -69,7 +66,7 @@ public class Runtime internal const string _pyversion = "3.8"; internal const string _pyver = "38"; #else -#error You must define one of PYTHON34 to PYTHON38 or PYTHON27 +#error You must define one of PYTHON34 to PYTHON38 #endif #if MONO_LINUX || MONO_OSX // Linux/macOS use dotted version string @@ -155,9 +152,6 @@ public class Runtime /// public static MachineType Machine { get; private set; }/* set in Initialize using python's platform.machine */ - internal static bool IsPython2 = pyversionnumber < 30; - internal static bool IsPython3 = pyversionnumber >= 30; - public static int MainManagedThreadId { get; private set; } /// @@ -244,12 +238,10 @@ internal static void Initialize(bool initSigs = false) () => PyUnicodeType = IntPtr.Zero); XDecref(op); -#if PYTHON3 op = PyBytes_FromString("bytes"); SetPyMember(ref PyBytesType, PyObject_Type(op), () => PyBytesType = IntPtr.Zero); XDecref(op); -#endif op = PyTuple_New(0); SetPyMember(ref PyTupleType, PyObject_Type(op), @@ -281,28 +273,8 @@ internal static void Initialize(bool initSigs = false) () => PyFloatType = IntPtr.Zero); XDecref(op); -#if !PYTHON2 PyClassType = IntPtr.Zero; PyInstanceType = IntPtr.Zero; -#else - { - IntPtr s = PyString_FromString("_temp"); - IntPtr d = PyDict_New(); - - IntPtr c = PyClass_New(IntPtr.Zero, d, s); - SetPyMember(ref PyClassType, PyObject_Type(c), - () => PyClassType = IntPtr.Zero); - - IntPtr i = PyInstance_New(c, IntPtr.Zero, IntPtr.Zero); - SetPyMember(ref PyInstanceType, PyObject_Type(i), - () => PyInstanceType = IntPtr.Zero); - - XDecref(s); - XDecref(i); - XDecref(c); - XDecref(d); - } -#endif Error = new IntPtr(-1); @@ -481,9 +453,7 @@ private static void ResetPyMembers() internal static IntPtr Py_NoSiteFlag; -#if PYTHON3 internal static IntPtr PyBytesType; -#endif internal static IntPtr _PyObject_NextNotImplemented; internal static IntPtr PyNotImplemented; @@ -758,16 +728,11 @@ internal static unsafe long Refcount(IntPtr op) [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyGILState_GetThisThreadState(); -#if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] public static extern int Py_Main( int argc, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv ); -#elif PYTHON2 - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] - public static extern int Py_Main(int argc, string[] argv); -#endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyEval_InitThreads(); @@ -839,19 +804,11 @@ public static extern int Py_Main( internal static extern int PyRun_SimpleString(string code); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] -#if PYTHON2 - internal static extern NewReference PyRun_String(string code, IntPtr st, IntPtr globals, IntPtr locals); -#else internal static extern NewReference PyRun_String([MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(Utf8Marshaler))] string code, IntPtr st, IntPtr globals, IntPtr locals); -#endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyEval_EvalCode(IntPtr co, IntPtr globals, IntPtr locals); -#if PYTHON2 - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] - internal static extern IntPtr Py_CompileString(string code, string file, int start); -#else /// /// Return value: New reference. /// This is a simplified interface to Py_CompileStringFlags() below, leaving flags set to NULL. @@ -877,7 +834,6 @@ internal static IntPtr Py_CompileStringFlags(string str, string file, int start, /// [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr Py_CompileStringExFlags(string str, string file, int start, IntPtr flags, int optimize); -#endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyImport_ExecCodeModule(string name, IntPtr code); @@ -888,11 +844,6 @@ internal static IntPtr Py_CompileStringFlags(string str, string file, int start, [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyCFunction_Call(IntPtr func, IntPtr args, IntPtr kw); -#if PYTHON2 - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] - internal static extern IntPtr PyClass_New(IntPtr bases, IntPtr dict, IntPtr name); -#endif - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyInstance_New(IntPtr cls, IntPtr args, IntPtr kw); @@ -954,11 +905,6 @@ internal static string PyObject_GetTypeName(IntPtr op) internal static bool PyObject_IsIterable(IntPtr pointer) { var ob_type = Marshal.ReadIntPtr(pointer, ObjectOffset.ob_type); -#if PYTHON2 - long tp_flags = Util.ReadCLong(ob_type, TypeOffset.tp_flags); - if ((tp_flags & TypeFlags.HaveIter) == 0) - return false; -#endif IntPtr tp_iter = Marshal.ReadIntPtr(ob_type, TypeOffset.tp_iter); return tp_iter != IntPtr.Zero; } @@ -999,7 +945,6 @@ internal static bool PyObject_IsIterable(IntPtr pointer) [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_CallObject(IntPtr pointer, IntPtr args); -#if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_RichCompareBool(IntPtr value1, IntPtr value2, int opid); @@ -1027,10 +972,6 @@ internal static int PyObject_Compare(IntPtr value1, IntPtr value2) Exceptions.SetError(Exceptions.SystemError, "Error comparing objects"); return -1; } -#elif PYTHON2 - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] - internal static extern int PyObject_Compare(IntPtr value1, IntPtr value2); -#endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_IsInstance(IntPtr ob, IntPtr type); @@ -1064,14 +1005,9 @@ internal static long PyObject_Size(IntPtr pointer) [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_Str(IntPtr pointer); -#if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyObject_Str")] internal static extern IntPtr PyObject_Unicode(IntPtr pointer); -#elif PYTHON2 - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] - internal static extern IntPtr PyObject_Unicode(IntPtr pointer); -#endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_Dir(IntPtr pointer); @@ -1081,14 +1017,9 @@ internal static long PyObject_Size(IntPtr pointer) // Python number API //==================================================================== -#if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyNumber_Long")] internal static extern IntPtr PyNumber_Int(IntPtr ob); -#elif PYTHON2 - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] - internal static extern IntPtr PyNumber_Int(IntPtr ob); -#endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Long(IntPtr ob); @@ -1121,7 +1052,6 @@ internal static IntPtr PyInt_FromInt64(long value) return PyInt_FromLong(v); } -#if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyLong_FromLong")] private static extern IntPtr PyInt_FromLong(IntPtr value); @@ -1133,19 +1063,6 @@ internal static IntPtr PyInt_FromInt64(long value) [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyLong_FromString")] internal static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); -#elif PYTHON2 - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] - private static extern IntPtr PyInt_FromLong(IntPtr value); - - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] - internal static extern int PyInt_AsLong(IntPtr value); - - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] - internal static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); - - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] - internal static extern int PyInt_GetMax(); -#endif internal static bool PyLong_Check(IntPtr ob) { @@ -1410,14 +1327,9 @@ internal static bool PyString_Check(IntPtr ob) internal static IntPtr PyString_FromString(string value) { -#if PYTHON3 return PyUnicode_FromKindAndData(_UCS, value, value.Length); -#elif PYTHON2 - return PyString_FromStringAndSize(value, value.Length); -#endif } -#if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyBytes_FromString(string op); @@ -1457,28 +1369,11 @@ internal static IntPtr PyUnicode_FromStringAndSize(IntPtr value, long size) [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyUnicode_AsUTF8(IntPtr unicode); -#elif PYTHON2 - internal static IntPtr PyString_FromStringAndSize(string value, long size) - { - return PyString_FromStringAndSize(value, new IntPtr(size)); - } - - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] - private static extern IntPtr PyString_FromStringAndSize(string value, IntPtr size); - - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] - internal static extern IntPtr PyString_AsString(IntPtr op); - - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] - internal static extern int PyString_Size(IntPtr pointer); -#endif - internal static bool PyUnicode_Check(IntPtr ob) { return PyObject_TYPE(ob) == PyUnicodeType; } -#if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); @@ -1515,44 +1410,6 @@ internal static long PyUnicode_GetSize(IntPtr ob) [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyUnicode_FromOrdinal(int c); -#elif PYTHON2 - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = PyUnicodeEntryPoint + "FromObject")] - internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); - - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = PyUnicodeEntryPoint + "FromEncodedObject")] - internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - - internal static IntPtr PyUnicode_FromUnicode(string s, long size) - { - return PyUnicode_FromUnicode(s, new IntPtr(size)); - } - - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = PyUnicodeEntryPoint + "FromUnicode")] - private static extern IntPtr PyUnicode_FromUnicode( - [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UcsMarshaler))] string s, - IntPtr size - ); - - internal static long PyUnicode_GetSize(IntPtr ob) - { - return (long) _PyUnicode_GetSize(ob); - } - - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = PyUnicodeEntryPoint + "GetSize")] - internal static extern IntPtr _PyUnicode_GetSize(IntPtr ob); - - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = PyUnicodeEntryPoint + "AsUnicode")] - internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = PyUnicodeEntryPoint + "FromOrdinal")] - internal static extern IntPtr PyUnicode_FromOrdinal(int c); -#endif internal static IntPtr PyUnicode_FromString(string s) { @@ -1578,13 +1435,6 @@ internal static string GetManagedString(IntPtr op) { IntPtr type = PyObject_TYPE(op); -#if PYTHON2 // Python 3 strings are all Unicode - if (type == PyStringType) - { - return Marshal.PtrToStringAnsi(PyString_AsString(op), PyString_Size(op)); - } -#endif - if (type == PyUnicodeType) { IntPtr p = PyUnicode_AsUnicode(op); @@ -1797,11 +1647,6 @@ internal static long PyTuple_Size(IntPtr pointer) internal static bool PyIter_Check(IntPtr pointer) { var ob_type = Marshal.ReadIntPtr(pointer, ObjectOffset.ob_type); -#if PYTHON2 - long tp_flags = Util.ReadCLong(ob_type, TypeOffset.tp_flags); - if ((tp_flags & TypeFlags.HaveIter) == 0) - return false; -#endif IntPtr tp_iternext = Marshal.ReadIntPtr(ob_type, TypeOffset.tp_iternext); return tp_iternext != IntPtr.Zero && tp_iternext != _PyObject_NextNotImplemented; } @@ -1826,10 +1671,8 @@ internal static bool PyIter_Check(IntPtr pointer) [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern string PyModule_GetFilename(IntPtr module); -#if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyModule_Create2(IntPtr module, int apiver); -#endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyImport_Import(IntPtr name); @@ -1849,21 +1692,12 @@ internal static bool PyIter_Check(IntPtr pointer) [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyImport_GetModuleDict(); -#if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PySys_SetArgvEx( int argc, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv, int updatepath ); -#elif PYTHON2 - [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] - internal static extern void PySys_SetArgvEx( - int argc, - string[] argv, - int updatepath - ); -#endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PySys_GetObject(string name); @@ -2054,8 +1888,7 @@ internal static void SetNoSiteFlag() /// internal static IntPtr GetBuiltins() { - return IsPython3 ? PyImport_ImportModule("builtins") - : PyImport_ImportModule("__builtin__"); + return PyImport_ImportModule("builtins"); } } diff --git a/src/runtime/typemanager.cs b/src/runtime/typemanager.cs index 3df873eb5..04d40a2ba 100644 --- a/src/runtime/typemanager.cs +++ b/src/runtime/typemanager.cs @@ -433,19 +433,12 @@ internal static IntPtr AllocateTypeObject(string name) // Cheat a little: we'll set tp_name to the internal char * of // the Python version of the type name - otherwise we'd have to // allocate the tp_name and would have no way to free it. -#if PYTHON3 IntPtr temp = Runtime.PyUnicode_FromString(name); IntPtr raw = Runtime.PyUnicode_AsUTF8(temp); -#elif PYTHON2 - IntPtr temp = Runtime.PyString_FromString(name); - IntPtr raw = Runtime.PyString_AsString(temp); -#endif Marshal.WriteIntPtr(type, TypeOffset.tp_name, raw); Marshal.WriteIntPtr(type, TypeOffset.name, temp); -#if PYTHON3 Marshal.WriteIntPtr(type, TypeOffset.qualname, temp); -#endif long ptr = type.ToInt64(); // 64-bit safe @@ -458,11 +451,7 @@ internal static IntPtr AllocateTypeObject(string name) temp = new IntPtr(ptr + TypeOffset.mp_length); Marshal.WriteIntPtr(type, TypeOffset.tp_as_mapping, temp); -#if PYTHON3 temp = new IntPtr(ptr + TypeOffset.bf_getbuffer); -#elif PYTHON2 - temp = new IntPtr(ptr + TypeOffset.bf_getreadbuffer); -#endif Marshal.WriteIntPtr(type, TypeOffset.tp_as_buffer, temp); return type; } From 7a348540185e50817ea14dc22b2e30d0c6c854d4 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Sun, 14 Jun 2020 16:47:35 +0200 Subject: [PATCH 2/8] Drop Python 2 tests --- src/runtime/interop37m.cs | 150 +++++++++++++++++++++++++++++++++++ src/tests/_compat.py | 63 +-------------- src/tests/leaktest.py | 1 - src/tests/profile.py | 1 - src/tests/runtests.py | 2 - src/tests/stress.py | 2 +- src/tests/stresstest.py | 2 - src/tests/test_array.py | 39 ++++----- src/tests/test_class.py | 2 +- src/tests/test_compat.py | 29 ++----- src/tests/test_conversion.py | 80 +++++++++---------- src/tests/test_enum.py | 20 ++--- src/tests/test_event.py | 1 - src/tests/test_exceptions.py | 6 +- src/tests/test_generic.py | 78 ++++++------------ src/tests/test_indexer.py | 18 ++--- src/tests/test_method.py | 57 +++++-------- src/tests/test_module.py | 27 ++----- src/tests/test_subclass.py | 2 - src/tests/test_thread.py | 2 +- src/tests/utils.py | 10 +-- 21 files changed, 291 insertions(+), 301 deletions(-) create mode 100644 src/runtime/interop37m.cs diff --git a/src/runtime/interop37m.cs b/src/runtime/interop37m.cs new file mode 100644 index 000000000..42e8e0f31 --- /dev/null +++ b/src/runtime/interop37m.cs @@ -0,0 +1,150 @@ + +// Auto-generated by geninterop.py. +// DO NOT MODIFY BY HAND. + + +#if PYTHON37 && PYTHON_WITH_PYMALLOC +using System; +using System.Collections; +using System.Collections.Specialized; +using System.Runtime.InteropServices; +using System.Reflection; +using System.Text; + +namespace Python.Runtime +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + internal class TypeOffset + { + static TypeOffset() + { + Type type = typeof(TypeOffset); + FieldInfo[] fi = type.GetFields(); + int size = IntPtr.Size; + for (int i = 0; i < fi.Length; i++) + { + fi[i].SetValue(null, i * size); + } + } + + public static int magic() + { + return ob_size; + } + + // Auto-generated from PyHeapTypeObject in Python.h + public static int ob_refcnt = 0; + public static int ob_type = 0; + public static int ob_size = 0; + public static int tp_name = 0; + public static int tp_basicsize = 0; + public static int tp_itemsize = 0; + public static int tp_dealloc = 0; + public static int tp_print = 0; + public static int tp_getattr = 0; + public static int tp_setattr = 0; + public static int tp_as_async = 0; + public static int tp_repr = 0; + public static int tp_as_number = 0; + public static int tp_as_sequence = 0; + public static int tp_as_mapping = 0; + public static int tp_hash = 0; + public static int tp_call = 0; + public static int tp_str = 0; + public static int tp_getattro = 0; + public static int tp_setattro = 0; + public static int tp_as_buffer = 0; + public static int tp_flags = 0; + public static int tp_doc = 0; + public static int tp_traverse = 0; + public static int tp_clear = 0; + public static int tp_richcompare = 0; + public static int tp_weaklistoffset = 0; + public static int tp_iter = 0; + public static int tp_iternext = 0; + public static int tp_methods = 0; + public static int tp_members = 0; + public static int tp_getset = 0; + public static int tp_base = 0; + public static int tp_dict = 0; + public static int tp_descr_get = 0; + public static int tp_descr_set = 0; + public static int tp_dictoffset = 0; + public static int tp_init = 0; + public static int tp_alloc = 0; + public static int tp_new = 0; + public static int tp_free = 0; + public static int tp_is_gc = 0; + public static int tp_bases = 0; + public static int tp_mro = 0; + public static int tp_cache = 0; + public static int tp_subclasses = 0; + public static int tp_weaklist = 0; + public static int tp_del = 0; + public static int tp_version_tag = 0; + public static int tp_finalize = 0; + public static int am_await = 0; + public static int am_aiter = 0; + public static int am_anext = 0; + public static int nb_add = 0; + public static int nb_subtract = 0; + public static int nb_multiply = 0; + public static int nb_remainder = 0; + public static int nb_divmod = 0; + public static int nb_power = 0; + public static int nb_negative = 0; + public static int nb_positive = 0; + public static int nb_absolute = 0; + public static int nb_bool = 0; + public static int nb_invert = 0; + public static int nb_lshift = 0; + public static int nb_rshift = 0; + public static int nb_and = 0; + public static int nb_xor = 0; + public static int nb_or = 0; + public static int nb_int = 0; + public static int nb_reserved = 0; + public static int nb_float = 0; + public static int nb_inplace_add = 0; + public static int nb_inplace_subtract = 0; + public static int nb_inplace_multiply = 0; + public static int nb_inplace_remainder = 0; + public static int nb_inplace_power = 0; + public static int nb_inplace_lshift = 0; + public static int nb_inplace_rshift = 0; + public static int nb_inplace_and = 0; + public static int nb_inplace_xor = 0; + public static int nb_inplace_or = 0; + public static int nb_floor_divide = 0; + public static int nb_true_divide = 0; + public static int nb_inplace_floor_divide = 0; + public static int nb_inplace_true_divide = 0; + public static int nb_index = 0; + public static int nb_matrix_multiply = 0; + public static int nb_inplace_matrix_multiply = 0; + public static int mp_length = 0; + public static int mp_subscript = 0; + public static int mp_ass_subscript = 0; + public static int sq_length = 0; + public static int sq_concat = 0; + public static int sq_repeat = 0; + public static int sq_item = 0; + public static int was_sq_slice = 0; + public static int sq_ass_item = 0; + public static int was_sq_ass_slice = 0; + public static int sq_contains = 0; + public static int sq_inplace_concat = 0; + public static int sq_inplace_repeat = 0; + public static int bf_getbuffer = 0; + public static int bf_releasebuffer = 0; + public static int name = 0; + public static int ht_slots = 0; + public static int qualname = 0; + public static int ht_cached_keys = 0; + + /* here are optional user slots, followed by the members. */ + public static int members = 0; + } +} + +#endif diff --git a/src/tests/_compat.py b/src/tests/_compat.py index 3751ca013..f44ca4649 100644 --- a/src/tests/_compat.py +++ b/src/tests/_compat.py @@ -5,70 +5,11 @@ Using Python 3 syntax to encourage upgrade unless otherwise noted. """ -import operator import subprocess -import sys -import types - -PY2 = sys.version_info[0] == 2 -PY3 = sys.version_info[0] == 3 - -if PY3: - import _thread as thread # Using PY2 name - import pickle - from collections import UserList - - indexbytes = operator.getitem - input = input - - string_types = str, - binary_type = bytes - text_type = str - - DictProxyType = type(object.__dict__) - ClassType = type - - # No PY3 equivalents, use PY2 name - long = int - unichr = chr - unicode = str - - # from nowhere import Nothing - cmp = lambda a, b: (a > b) - (a < b) # No PY3 equivalent - map = map - range = range - zip = zip - -elif PY2: - import thread # Using PY2 name - import cPickle as pickle - from UserList import UserList - - indexbytes = lambda buf, i: ord(buf[i]) - input = raw_input - - string_types = str, unicode - bytes_type = str - text_type = unicode - - DictProxyType = types.DictProxyType - ClassType = types.ClassType - - # No PY3 equivalents, use PY2 name - long = long - unichr = unichr - unicode = unicode - - from itertools import izip, imap - cmp = cmp - map = imap - range = xrange - zip = izip - +import _thread as thread +DictProxyType = type(object.__dict__) def check_output(*args, **kwargs): """Check output wrapper for PY2/PY3 compatibility""" output = subprocess.check_output(*args, **kwargs) - if PY2: - return output return output.decode("ascii") diff --git a/src/tests/leaktest.py b/src/tests/leaktest.py index 05b76e867..02133fece 100644 --- a/src/tests/leaktest.py +++ b/src/tests/leaktest.py @@ -10,7 +10,6 @@ import System -from ._compat import range from .utils import (CallableHandler, ClassMethodHandler, GenericHandler, HelloClass, StaticMethodHandler, VarCallableHandler, VariableArgsHandler, hello_func) diff --git a/src/tests/profile.py b/src/tests/profile.py index 4af3589e8..2113b1727 100644 --- a/src/tests/profile.py +++ b/src/tests/profile.py @@ -14,7 +14,6 @@ import time import runtests -from ._compat import range def main(): diff --git a/src/tests/runtests.py b/src/tests/runtests.py index 8011d05e6..9b90bcf6a 100644 --- a/src/tests/runtests.py +++ b/src/tests/runtests.py @@ -8,8 +8,6 @@ import sys import pytest -from ._compat import input - try: import System except ImportError: diff --git a/src/tests/stress.py b/src/tests/stress.py index c6fa8b7e3..b5a67b124 100644 --- a/src/tests/stress.py +++ b/src/tests/stress.py @@ -17,7 +17,7 @@ import threading import time -from ._compat import range, thread +from ._compat import thread from .utils import dprint diff --git a/src/tests/stresstest.py b/src/tests/stresstest.py index 74b863bdc..b0dca9461 100644 --- a/src/tests/stresstest.py +++ b/src/tests/stresstest.py @@ -11,8 +11,6 @@ import unittest # import pdb -from ._compat import range - try: import System except ImportError: diff --git a/src/tests/test_array.py b/src/tests/test_array.py index b492a66d3..427958ec7 100644 --- a/src/tests/test_array.py +++ b/src/tests/test_array.py @@ -6,7 +6,7 @@ import System import pytest -from ._compat import PY2, UserList, long, range, unichr +from collections import UserList def test_public_array(): @@ -246,8 +246,8 @@ def test_char_array(): assert items[0] == 'a' assert items[4] == 'e' - max_ = unichr(65535) - min_ = unichr(0) + max_ = chr(65535) + min_ = chr(0) items[0] = max_ assert items[0] == max_ @@ -364,8 +364,8 @@ def test_int64_array(): assert items[0] == 0 assert items[4] == 4 - max_ = long(9223372036854775807) - min_ = long(-9223372036854775808) + max_ = 9223372036854775807 + min_ = -9223372036854775808 items[0] = max_ assert items[0] == max_ @@ -448,7 +448,7 @@ def test_uint32_array(): assert items[0] == 0 assert items[4] == 4 - max_ = long(4294967295) + max_ = 4294967295 min_ = 0 items[0] = max_ @@ -490,7 +490,7 @@ def test_uint64_array(): assert items[0] == 0 assert items[4] == 4 - max_ = long(18446744073709551615) + max_ = 18446744073709551615 min_ = 0 items[0] = max_ @@ -1204,8 +1204,8 @@ def test_special_array_creation(): assert value.Length == 2 value = Array[System.Char]([0, 65535]) - assert value[0] == unichr(0) - assert value[1] == unichr(65535) + assert value[0] == chr(0) + assert value[1] == chr(65535) assert value.Length == 2 value = Array[System.Int16]([0, 32767]) @@ -1223,31 +1223,24 @@ def test_special_array_creation(): assert value[1] == 2147483647 assert value.Length == 2 - value = Array[System.Int64]([0, long(9223372036854775807)]) + value = Array[System.Int64]([0, 9223372036854775807]) assert value[0] == 0 - assert value[1] == long(9223372036854775807) + assert value[1] == 9223372036854775807 assert value.Length == 2 - # there's no explicit long type in python3, use System.Int64 instead - if PY2: - value = Array[long]([0, long(9223372036854775807)]) - assert value[0] == 0 - assert value[1] == long(9223372036854775807) - assert value.Length == 2 - value = Array[System.UInt16]([0, 65000]) assert value[0] == 0 assert value[1] == 65000 assert value.Length == 2 - value = Array[System.UInt32]([0, long(4294967295)]) + value = Array[System.UInt32]([0, 4294967295]) assert value[0] == 0 - assert value[1] == long(4294967295) + assert value[1] == 4294967295 assert value.Length == 2 - value = Array[System.UInt64]([0, long(18446744073709551615)]) + value = Array[System.UInt64]([0, 18446744073709551615]) assert value[0] == 0 - assert value[1] == long(18446744073709551615) + assert value[1] == 18446744073709551615 assert value.Length == 2 value = Array[System.Single]([0.0, 3.402823e38]) @@ -1339,7 +1332,6 @@ def test_array_abuse(): desc(0, 0, 0) -@pytest.mark.skipif(PY2, reason="Only applies in Python 3") def test_iterator_to_array(): from System import Array, String @@ -1354,7 +1346,6 @@ def test_iterator_to_array(): assert arr[2] == "c" -@pytest.mark.skipif(PY2, reason="Only applies in Python 3") def test_dict_keys_to_array(): from System import Array, String diff --git a/src/tests/test_class.py b/src/tests/test_class.py index 6db3c36b7..ecc8b56fb 100644 --- a/src/tests/test_class.py +++ b/src/tests/test_class.py @@ -7,7 +7,7 @@ import System import pytest -from ._compat import DictProxyType, range +from ._compat import DictProxyType def test_basic_reference_type(): diff --git a/src/tests/test_compat.py b/src/tests/test_compat.py index 81e7f8143..1c9f80e65 100644 --- a/src/tests/test_compat.py +++ b/src/tests/test_compat.py @@ -7,7 +7,6 @@ import pytest -from ._compat import ClassType, PY2, PY3, range from .utils import is_clr_class, is_clr_module, is_clr_root_module @@ -22,15 +21,9 @@ def test_simple_import(): assert isinstance(sys, types.ModuleType) assert sys.__name__ == 'sys' - if PY3: - import http.client - assert isinstance(http.client, types.ModuleType) - assert http.client.__name__ == 'http.client' - - elif PY2: - import httplib - assert isinstance(httplib, types.ModuleType) - assert httplib.__name__ == 'httplib' + import http.client + assert isinstance(http.client, types.ModuleType) + assert http.client.__name__ == 'http.client' def test_simple_import_with_alias(): @@ -43,15 +36,9 @@ def test_simple_import_with_alias(): assert isinstance(mySys, types.ModuleType) assert mySys.__name__ == 'sys' - if PY3: - import http.client as myHttplib - assert isinstance(myHttplib, types.ModuleType) - assert myHttplib.__name__ == 'http.client' - - elif PY2: - import httplib as myHttplib - assert isinstance(myHttplib, types.ModuleType) - assert myHttplib.__name__ == 'httplib' + import http.client as myHttplib + assert isinstance(myHttplib, types.ModuleType) + assert myHttplib.__name__ == 'http.client' def test_dotted_name_import(): @@ -125,7 +112,7 @@ def test_dotted_name_import_from(): assert pulldom.__name__ == 'xml.dom.pulldom' from xml.dom.pulldom import PullDOM - assert isinstance(PullDOM, ClassType) + assert isinstance(PullDOM, type) assert PullDOM.__name__ == 'PullDOM' @@ -144,7 +131,7 @@ def test_dotted_name_import_from_with_alias(): assert myPulldom.__name__ == 'xml.dom.pulldom' from xml.dom.pulldom import PullDOM as myPullDOM - assert isinstance(myPullDOM, ClassType) + assert isinstance(myPullDOM, type) assert myPullDOM.__name__ == 'PullDOM' diff --git a/src/tests/test_conversion.py b/src/tests/test_conversion.py index 1386a0358..6a4698157 100644 --- a/src/tests/test_conversion.py +++ b/src/tests/test_conversion.py @@ -9,8 +9,6 @@ from Python.Runtime import PyObjectConversions from Python.Runtime.Codecs import RawProxyEncoder -from ._compat import indexbytes, long, unichr, text_type, PY2, PY3 - def test_bool_conversion(): """Test bool conversion.""" @@ -145,8 +143,8 @@ def test_byte_conversion(): def test_char_conversion(): """Test char conversion.""" - assert System.Char.MaxValue == unichr(65535) - assert System.Char.MinValue == unichr(0) + assert System.Char.MaxValue == chr(65535) + assert System.Char.MinValue == chr(0) ob = ConversionTest() assert ob.CharField == u'A' @@ -250,23 +248,23 @@ def test_int32_conversion(): def test_int64_conversion(): """Test int64 conversion.""" - assert System.Int64.MaxValue == long(9223372036854775807) - assert System.Int64.MinValue == long(-9223372036854775808) + assert System.Int64.MaxValue == 9223372036854775807 + assert System.Int64.MinValue == -9223372036854775808 ob = ConversionTest() assert ob.Int64Field == 0 - ob.Int64Field = long(9223372036854775807) - assert ob.Int64Field == long(9223372036854775807) + ob.Int64Field = 9223372036854775807 + assert ob.Int64Field == 9223372036854775807 - ob.Int64Field = long(-9223372036854775808) - assert ob.Int64Field == long(-9223372036854775808) + ob.Int64Field = -9223372036854775808 + assert ob.Int64Field == -9223372036854775808 - ob.Int64Field = System.Int64(long(9223372036854775807)) - assert ob.Int64Field == long(9223372036854775807) + ob.Int64Field = System.Int64(9223372036854775807) + assert ob.Int64Field == 9223372036854775807 - ob.Int64Field = System.Int64(long(-9223372036854775808)) - assert ob.Int64Field == long(-9223372036854775808) + ob.Int64Field = System.Int64(-9223372036854775808) + assert ob.Int64Field == -9223372036854775808 with pytest.raises(TypeError): ConversionTest().Int64Field = "spam" @@ -275,16 +273,16 @@ def test_int64_conversion(): ConversionTest().Int64Field = None with pytest.raises(OverflowError): - ConversionTest().Int64Field = long(9223372036854775808) + ConversionTest().Int64Field = 9223372036854775808 with pytest.raises(OverflowError): - ConversionTest().Int64Field = long(-9223372036854775809) + ConversionTest().Int64Field = -9223372036854775809 with pytest.raises(OverflowError): - _ = System.Int64(long(9223372036854775808)) + _ = System.Int64(9223372036854775808) with pytest.raises(OverflowError): - _ = System.Int64(long(-9223372036854775809)) + _ = System.Int64(-9223372036854775809) def test_uint16_conversion(): @@ -328,20 +326,20 @@ def test_uint16_conversion(): def test_uint32_conversion(): """Test uint32 conversion.""" - assert System.UInt32.MaxValue == long(4294967295) + assert System.UInt32.MaxValue == 4294967295 assert System.UInt32.MinValue == 0 ob = ConversionTest() assert ob.UInt32Field == 0 - ob.UInt32Field = long(4294967295) - assert ob.UInt32Field == long(4294967295) + ob.UInt32Field = 4294967295 + assert ob.UInt32Field == 4294967295 ob.UInt32Field = -0 assert ob.UInt32Field == 0 - ob.UInt32Field = System.UInt32(long(4294967295)) - assert ob.UInt32Field == long(4294967295) + ob.UInt32Field = System.UInt32(4294967295) + assert ob.UInt32Field == 4294967295 ob.UInt32Field = System.UInt32(0) assert ob.UInt32Field == 0 @@ -353,13 +351,13 @@ def test_uint32_conversion(): ConversionTest().UInt32Field = None with pytest.raises(OverflowError): - ConversionTest().UInt32Field = long(4294967296) + ConversionTest().UInt32Field = 4294967296 with pytest.raises(OverflowError): ConversionTest().UInt32Field = -1 with pytest.raises(OverflowError): - _ = System.UInt32(long(4294967296)) + _ = System.UInt32(4294967296) with pytest.raises(OverflowError): _ = System.UInt32(-1) @@ -367,20 +365,20 @@ def test_uint32_conversion(): def test_uint64_conversion(): """Test uint64 conversion.""" - assert System.UInt64.MaxValue == long(18446744073709551615) + assert System.UInt64.MaxValue == 18446744073709551615 assert System.UInt64.MinValue == 0 ob = ConversionTest() assert ob.UInt64Field == 0 - ob.UInt64Field = long(18446744073709551615) - assert ob.UInt64Field == long(18446744073709551615) + ob.UInt64Field = 18446744073709551615 + assert ob.UInt64Field == 18446744073709551615 ob.UInt64Field = -0 assert ob.UInt64Field == 0 - ob.UInt64Field = System.UInt64(long(18446744073709551615)) - assert ob.UInt64Field == long(18446744073709551615) + ob.UInt64Field = System.UInt64(18446744073709551615) + assert ob.UInt64Field == 18446744073709551615 ob.UInt64Field = System.UInt64(0) assert ob.UInt64Field == 0 @@ -392,13 +390,13 @@ def test_uint64_conversion(): ConversionTest().UInt64Field = None with pytest.raises(OverflowError): - ConversionTest().UInt64Field = long(18446744073709551616) + ConversionTest().UInt64Field = 18446744073709551616 with pytest.raises(OverflowError): ConversionTest().UInt64Field = -1 with pytest.raises(OverflowError): - _ = System.UInt64(long(18446744073709551616)) + _ = System.UInt64((18446744073709551616)) with pytest.raises(OverflowError): _ = System.UInt64(-1) @@ -478,7 +476,7 @@ def test_decimal_conversion(): max_d = Decimal.Parse("79228162514264337593543950335") min_d = Decimal.Parse("-79228162514264337593543950335") - assert Decimal.ToInt64(Decimal(10)) == long(10) + assert Decimal.ToInt64(Decimal(10)) == 10 ob = ConversionTest() assert ob.DecimalField == Decimal(0) @@ -538,14 +536,12 @@ def test_string_conversion(): with pytest.raises(TypeError): ConversionTest().StringField = 1 - + world = UnicodeString() test_unicode_str = u"안녕" - assert test_unicode_str == text_type(world.value) - assert test_unicode_str == text_type(world.GetString()) - # TODO: not sure what to do for Python 2 here (GH PR #670) - if PY3: - assert test_unicode_str == text_type(world) + assert test_unicode_str == str(world.value) + assert test_unicode_str == str(world.GetString()) + assert test_unicode_str == (world) def test_interface_conversion(): @@ -641,7 +637,7 @@ def test_enum_conversion(): def test_null_conversion(): """Test null conversion.""" import System - + ob = ConversionTest() ob.StringField = None @@ -682,7 +678,7 @@ def test_byte_array_conversion(): ob.ByteArrayField = value array = ob.ByteArrayField for i, _ in enumerate(value): - assert array[i] == indexbytes(value, i) + assert array[i] == operator.getitem(value, i) def test_sbyte_array_conversion(): @@ -701,7 +697,7 @@ def test_sbyte_array_conversion(): ob.SByteArrayField = value array = ob.SByteArrayField for i, _ in enumerate(value): - assert array[i] == indexbytes(value, i) + assert array[i] == operator.getitem(value, i) def test_codecs(): """Test codec registration from Python""" diff --git a/src/tests/test_enum.py b/src/tests/test_enum.py index b31ce4ec5..7ca816eec 100644 --- a/src/tests/test_enum.py +++ b/src/tests/test_enum.py @@ -5,7 +5,7 @@ import pytest import Python.Test as Test -from ._compat import DictProxyType, long +from ._compat import DictProxyType def test_enum_standard_attrs(): @@ -68,23 +68,23 @@ def test_int_enum(): def test_uint_enum(): """Test uint enum.""" - assert Test.UIntEnum.Zero == long(0) - assert Test.UIntEnum.One == long(1) - assert Test.UIntEnum.Two == long(2) + assert Test.UIntEnum.Zero == 0 + assert Test.UIntEnum.One == 1 + assert Test.UIntEnum.Two == 2 def test_long_enum(): """Test long enum.""" - assert Test.LongEnum.Zero == long(0) - assert Test.LongEnum.One == long(1) - assert Test.LongEnum.Two == long(2) + assert Test.LongEnum.Zero == 0 + assert Test.LongEnum.One == 1 + assert Test.LongEnum.Two == 2 def test_ulong_enum(): """Test ulong enum.""" - assert Test.ULongEnum.Zero == long(0) - assert Test.ULongEnum.One == long(1) - assert Test.ULongEnum.Two == long(2) + assert Test.ULongEnum.Zero == 0 + assert Test.ULongEnum.One == 1 + assert Test.ULongEnum.Two == 2 def test_instantiate_enum_fails(): diff --git a/src/tests/test_event.py b/src/tests/test_event.py index 624b83d44..e9c0ffd8a 100644 --- a/src/tests/test_event.py +++ b/src/tests/test_event.py @@ -5,7 +5,6 @@ import pytest from Python.Test import EventTest, EventArgsTest -from ._compat import range from .utils import (CallableHandler, ClassMethodHandler, GenericHandler, MultipleHandler, StaticMethodHandler, VarCallableHandler, VariableArgsHandler) diff --git a/src/tests/test_exceptions.py b/src/tests/test_exceptions.py index c2f18d443..842f35bca 100644 --- a/src/tests/test_exceptions.py +++ b/src/tests/test_exceptions.py @@ -6,8 +6,7 @@ import System import pytest - -from ._compat import PY2, PY3, pickle, text_type +import pickle def test_unified_exception_semantics(): @@ -278,7 +277,7 @@ def test_python_compat_of_managed_exceptions(): e = OverflowException(msg) assert str(e) == msg - assert text_type(e) == msg + assert str(e) == msg assert e.args == (msg,) assert isinstance(e.args, tuple) @@ -321,7 +320,6 @@ def test_pickling_exceptions(): assert exc.args == loaded.args -@pytest.mark.skipif(PY2, reason="__cause__ isn't implemented in PY2") def test_chained_exceptions(): from Python.Test import ExceptionTest diff --git a/src/tests/test_generic.py b/src/tests/test_generic.py index 69cd4ee7f..fc40e8e43 100644 --- a/src/tests/test_generic.py +++ b/src/tests/test_generic.py @@ -7,8 +7,6 @@ import System import pytest -from ._compat import PY2, long, unicode, unichr, zip - def assert_generic_wrapper_by_type(ptype, value): """Test Helper""" @@ -139,13 +137,13 @@ def test_python_type_aliasing(): dict_ = Dictionary[long, long]() assert dict_.Count == 0 - dict_.Add(long(1), long(1)) - assert dict_[long(1)] == long(1) + dict_.Add(1, 1) + assert dict_[1] == 1 dict_ = Dictionary[System.Int64, System.Int64]() assert dict_.Count == 0 - dict_.Add(long(1), long(1)) - assert dict_[long(1)] == long(1) + dict_.Add(1, 1) + assert dict_[1] == 1 dict_ = Dictionary[float, float]() assert dict_.Count == 0 @@ -257,19 +255,15 @@ def test_generic_type_binding(): assert_generic_wrapper_by_type(System.Int16, 32767) assert_generic_wrapper_by_type(System.Int32, 2147483647) assert_generic_wrapper_by_type(int, 2147483647) - assert_generic_wrapper_by_type(System.Int64, long(9223372036854775807)) - # Python 3 has no explicit long type, use System.Int64 instead - if PY2: - assert_generic_wrapper_by_type(long, long(9223372036854775807)) + assert_generic_wrapper_by_type(System.Int64, 9223372036854775807) assert_generic_wrapper_by_type(System.UInt16, 65000) - assert_generic_wrapper_by_type(System.UInt32, long(4294967295)) - assert_generic_wrapper_by_type(System.UInt64, long(18446744073709551615)) + assert_generic_wrapper_by_type(System.UInt32, 4294967295) + assert_generic_wrapper_by_type(System.UInt64, 18446744073709551615) assert_generic_wrapper_by_type(System.Single, 3.402823e38) assert_generic_wrapper_by_type(System.Double, 1.7976931348623157e308) assert_generic_wrapper_by_type(float, 1.7976931348623157e308) assert_generic_wrapper_by_type(System.Decimal, System.Decimal.One) assert_generic_wrapper_by_type(System.String, "test") - assert_generic_wrapper_by_type(unicode, "test") assert_generic_wrapper_by_type(str, "test") assert_generic_wrapper_by_type(ShortEnum, ShortEnum.Zero) assert_generic_wrapper_by_type(System.Object, InterfaceTest()) @@ -315,19 +309,12 @@ def test_generic_method_type_handling(): assert_generic_method_by_type(System.Int16, 32767) assert_generic_method_by_type(System.Int32, 2147483647) assert_generic_method_by_type(int, 2147483647) - # Python 3 has no explicit long type, use System.Int64 instead - if PY2: - assert_generic_method_by_type(System.Int64, long(9223372036854775807)) - assert_generic_method_by_type(long, long(9223372036854775807)) - assert_generic_method_by_type(System.UInt32, long(4294967295)) - assert_generic_method_by_type(System.Int64, long(1844674407370955161)) assert_generic_method_by_type(System.UInt16, 65000) assert_generic_method_by_type(System.Single, 3.402823e38) assert_generic_method_by_type(System.Double, 1.7976931348623157e308) assert_generic_method_by_type(float, 1.7976931348623157e308) assert_generic_method_by_type(System.Decimal, System.Decimal.One) assert_generic_method_by_type(System.String, "test") - assert_generic_method_by_type(unicode, "test") assert_generic_method_by_type(str, "test") assert_generic_method_by_type(ShortEnum, ShortEnum.Zero) assert_generic_method_by_type(System.Object, InterfaceTest()) @@ -355,8 +342,6 @@ def test_correct_overload_selection(): assert Math.Max(atype(value1), atype(value2)) == Math.Max.__overloads__[atype, atype]( atype(value1), atype(value2)) - if PY2 and atype is Int64: - value2 = long(value2) assert Math.Max(atype(value1), value2) == Math.Max.__overloads__[atype, atype]( atype(value1), atype(value2)) @@ -481,7 +466,7 @@ def test_method_overload_selection_with_generic_types(): vtype = GenericWrapper[System.Char] input_ = vtype(65535) value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value.value == unichr(65535) + assert value.value == chr(65535) vtype = GenericWrapper[System.Int16] input_ = vtype(32767) @@ -499,16 +484,9 @@ def test_method_overload_selection_with_generic_types(): assert value.value == 2147483647 vtype = GenericWrapper[System.Int64] - input_ = vtype(long(9223372036854775807)) + input_ = vtype(9223372036854775807) value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value.value == long(9223372036854775807) - - # Python 3 has no explicit long type, use System.Int64 instead - if PY2: - vtype = GenericWrapper[long] - input_ = vtype(long(9223372036854775807)) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value.value == long(9223372036854775807) + assert value.value == 9223372036854775807 vtype = GenericWrapper[System.UInt16] input_ = vtype(65000) @@ -516,14 +494,14 @@ def test_method_overload_selection_with_generic_types(): assert value.value == 65000 vtype = GenericWrapper[System.UInt32] - input_ = vtype(long(4294967295)) + input_ = vtype(4294967295) value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value.value == long(4294967295) + assert value.value == 4294967295 vtype = GenericWrapper[System.UInt64] - input_ = vtype(long(18446744073709551615)) + input_ = vtype(18446744073709551615) value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value.value == long(18446744073709551615) + assert value.value == 18446744073709551615 vtype = GenericWrapper[System.Single] input_ = vtype(3.402823e38) @@ -628,7 +606,7 @@ def test_overload_selection_with_arrays_of_generic_types(): vtype = System.Array[gtype] input_ = vtype([gtype(65535), gtype(65535)]) value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value[0].value == unichr(65535) + assert value[0].value == chr(65535) assert value.Length == 2 gtype = GenericWrapper[System.Int16] @@ -654,22 +632,12 @@ def test_overload_selection_with_arrays_of_generic_types(): gtype = GenericWrapper[System.Int64] vtype = System.Array[gtype] - input_ = vtype([gtype(long(9223372036854775807)), - gtype(long(9223372036854775807))]) + input_ = vtype([gtype(9223372036854775807), + gtype(9223372036854775807)]) value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value[0].value == long(9223372036854775807) + assert value[0].value == 9223372036854775807 assert value.Length == 2 - # Python 3 has no explicit long type, use System.Int64 instead - if PY2: - gtype = GenericWrapper[long] - vtype = System.Array[gtype] - input_ = vtype([gtype(long(9223372036854775807)), - gtype(long(9223372036854775807))]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value[0].value == long(9223372036854775807) - assert value.Length == 2 - gtype = GenericWrapper[System.UInt16] vtype = System.Array[gtype] input_ = vtype([gtype(65000), gtype(65000)]) @@ -679,17 +647,17 @@ def test_overload_selection_with_arrays_of_generic_types(): gtype = GenericWrapper[System.UInt32] vtype = System.Array[gtype] - input_ = vtype([gtype(long(4294967295)), gtype(long(4294967295))]) + input_ = vtype([gtype(4294967295), gtype(4294967295)]) value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value[0].value == long(4294967295) + assert value[0].value == 4294967295 assert value.Length == 2 gtype = GenericWrapper[System.UInt64] vtype = System.Array[gtype] - input_ = vtype([gtype(long(18446744073709551615)), - gtype(long(18446744073709551615))]) + input_ = vtype([gtype(18446744073709551615), + gtype(18446744073709551615)]) value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value[0].value == long(18446744073709551615) + assert value[0].value == 18446744073709551615 assert value.Length == 2 gtype = GenericWrapper[System.Single] diff --git a/src/tests/test_indexer.py b/src/tests/test_indexer.py index ca4fd3b89..6a36a2519 100644 --- a/src/tests/test_indexer.py +++ b/src/tests/test_indexer.py @@ -5,8 +5,6 @@ import Python.Test as Test import pytest -from ._compat import long, unichr - def test_public_indexer(): """Test public indexers.""" @@ -131,8 +129,8 @@ def test_sbyte_indexer(): def test_char_indexer(): """Test char indexers.""" ob = Test.CharIndexerTest() - max_ = unichr(65535) - min_ = unichr(0) + max_ = chr(65535) + min_ = chr(0) assert ob[max_] is None @@ -200,8 +198,8 @@ def test_int32_indexer(): def test_int64_indexer(): """Test Int64 indexers.""" ob = Test.Int64IndexerTest() - max_ = long(9223372036854775807) - min_ = long(-9223372036854775808) + max_ = 9223372036854775807 + min_ = -9223372036854775808 assert ob[max_] is None @@ -246,7 +244,7 @@ def test_uint16_indexer(): def test_uint32_indexer(): """Test UInt32 indexers.""" ob = Test.UInt32IndexerTest() - max_ = long(4294967295) + max_ = 4294967295 min_ = 0 assert ob[max_] is None @@ -269,7 +267,7 @@ def test_uint32_indexer(): def test_uint64_indexer(): """Test UInt64 indexers.""" ob = Test.UInt64IndexerTest() - max_ = long(18446744073709551615) + max_ = 18446744073709551615 min_ = 0 assert ob[max_] is None @@ -435,8 +433,8 @@ def test_object_indexer(): ob[1] = "one" assert ob[1] == "one" - ob[long(1)] = "long" - assert ob[long(1)] == "long" + ob[1] = "long" + assert ob[1] == "long" class Eggs(object): pass diff --git a/src/tests/test_method.py b/src/tests/test_method.py index 69f1b5e72..d9c033802 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -6,8 +6,6 @@ import pytest from Python.Test import MethodTest -from ._compat import PY2, long, unichr - def test_instance_method_descriptor(): """Test instance method descriptor behavior.""" @@ -504,7 +502,7 @@ def test_explicit_overload_selection(): assert value == u'A' value = MethodTest.Overloaded.__overloads__[System.Char](65535) - assert value == unichr(65535) + assert value == chr(65535) value = MethodTest.Overloaded.__overloads__[System.Int16](32767) assert value == 32767 @@ -516,25 +514,22 @@ def test_explicit_overload_selection(): assert value == 2147483647 value = MethodTest.Overloaded.__overloads__[System.Int64]( - long(9223372036854775807)) - assert value == long(9223372036854775807) - - # Python 3 has no explicit long type, use System.Int64 instead - if PY2: - value = MethodTest.Overloaded.__overloads__[long]( - long(9223372036854775807)) - assert value == long(9223372036854775807) + 9223372036854775807 + ) + assert value == 9223372036854775807 value = MethodTest.Overloaded.__overloads__[System.UInt16](65000) assert value == 65000 value = MethodTest.Overloaded.__overloads__[System.UInt32]( - long(4294967295)) - assert value == long(4294967295) + 4294967295 + ) + assert value == 4294967295 value = MethodTest.Overloaded.__overloads__[System.UInt64]( - long(18446744073709551615)) - assert value == long(18446744073709551615) + 18446744073709551615 + ) + assert value == 18446744073709551615 value = MethodTest.Overloaded.__overloads__[System.Single](3.402823e38) assert value == 3.402823e38 @@ -621,8 +616,8 @@ def test_overload_selection_with_array_types(): vtype = Array[System.Char] input_ = vtype([0, 65535]) value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value[0] == unichr(0) - assert value[1] == unichr(65535) + assert value[0] == chr(0) + assert value[1] == chr(65535) vtype = Array[System.Int16] input_ = vtype([0, 32767]) @@ -643,18 +638,10 @@ def test_overload_selection_with_array_types(): assert value[1] == 2147483647 vtype = Array[System.Int64] - input_ = vtype([0, long(9223372036854775807)]) + input_ = vtype([0, 9223372036854775807]) value = MethodTest.Overloaded.__overloads__[vtype](input_) assert value[0] == 0 - assert value[1] == long(9223372036854775807) - - # Python 3 has no explicit long type, use System.Int64 instead - if PY2: - vtype = Array[long] - input_ = vtype([0, long(9223372036854775807)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value[0] == 0 - assert value[1] == long(9223372036854775807) + assert value[1] == 9223372036854775807 vtype = Array[System.UInt16] input_ = vtype([0, 65000]) @@ -663,16 +650,16 @@ def test_overload_selection_with_array_types(): assert value[1] == 65000 vtype = Array[System.UInt32] - input_ = vtype([0, long(4294967295)]) + input_ = vtype([0, 4294967295]) value = MethodTest.Overloaded.__overloads__[vtype](input_) assert value[0] == 0 - assert value[1] == long(4294967295) + assert value[1] == 4294967295 vtype = Array[System.UInt64] - input_ = vtype([0, long(18446744073709551615)]) + input_ = vtype([0, 18446744073709551615]) value = MethodTest.Overloaded.__overloads__[vtype](input_) assert value[0] == 0 - assert value[1] == long(18446744073709551615) + assert value[1] == 18446744073709551615 vtype = Array[System.Single] input_ = vtype([0.0, 3.402823e38]) @@ -748,7 +735,7 @@ def test_explicit_overload_selection_failure(): _ = MethodTest.Overloaded.__overloads__[str, int, int]("", 1, 1) with pytest.raises(TypeError): - _ = MethodTest.Overloaded.__overloads__[int, long](1) + _ = MethodTest.Overloaded.__overloads__[int, int](1) def test_we_can_bind_to_encoding_get_string(): @@ -807,7 +794,7 @@ def test_no_object_in_param(): res = MethodTest.TestOverloadedNoObject(5) assert res == "Got int" - + res = MethodTest.TestOverloadedNoObject(i=7) assert res == "Got int" @@ -821,13 +808,13 @@ def test_object_in_param(): res = MethodTest.TestOverloadedObject(5) assert res == "Got int" - + res = MethodTest.TestOverloadedObject(i=7) assert res == "Got int" res = MethodTest.TestOverloadedObject("test") assert res == "Got object" - + res = MethodTest.TestOverloadedObject(o="test") assert res == "Got object" diff --git a/src/tests/test_module.py b/src/tests/test_module.py index 62d79b9ab..2b1a9e4ec 100644 --- a/src/tests/test_module.py +++ b/src/tests/test_module.py @@ -10,7 +10,6 @@ import pytest -from ._compat import ClassType, PY2, PY3, range from .utils import is_clr_class, is_clr_module, is_clr_root_module @@ -79,14 +78,9 @@ def test_simple_import(): assert isinstance(sys, types.ModuleType) assert sys.__name__ == 'sys' - if PY3: - import http.client as httplib - assert isinstance(httplib, types.ModuleType) - assert httplib.__name__ == 'http.client' - elif PY2: - import httplib - assert isinstance(httplib, types.ModuleType) - assert httplib.__name__ == 'httplib' + import http.client as httplib + assert isinstance(httplib, types.ModuleType) + assert httplib.__name__ == 'http.client' def test_simple_import_with_alias(): @@ -99,14 +93,9 @@ def test_simple_import_with_alias(): assert isinstance(mySys, types.ModuleType) assert mySys.__name__ == 'sys' - if PY3: - import http.client as myHttplib - assert isinstance(myHttplib, types.ModuleType) - assert myHttplib.__name__ == 'http.client' - elif PY2: - import httplib as myHttplib - assert isinstance(myHttplib, types.ModuleType) - assert myHttplib.__name__ == 'httplib' + import http.client as myHttplib + assert isinstance(myHttplib, types.ModuleType) + assert myHttplib.__name__ == 'http.client' def test_dotted_name_import(): @@ -178,7 +167,7 @@ def test_dotted_name_import_from(): assert pulldom.__name__ == 'xml.dom.pulldom' from xml.dom.pulldom import PullDOM - assert isinstance(PullDOM, ClassType) + assert isinstance(PullDOM, type) assert PullDOM.__name__ == 'PullDOM' @@ -197,7 +186,7 @@ def test_dotted_name_import_from_with_alias(): assert myPulldom.__name__ == 'xml.dom.pulldom' from xml.dom.pulldom import PullDOM as myPullDOM - assert isinstance(myPullDOM, ClassType) + assert isinstance(myPullDOM, type) assert myPullDOM.__name__ == 'PullDOM' diff --git a/src/tests/test_subclass.py b/src/tests/test_subclass.py index ab440d429..07eaf7f82 100644 --- a/src/tests/test_subclass.py +++ b/src/tests/test_subclass.py @@ -12,8 +12,6 @@ FunctionsTest) from System.Collections.Generic import List -from ._compat import range - def interface_test_class_fixture(subnamespace): """Delay creation of class until test starts.""" diff --git a/src/tests/test_thread.py b/src/tests/test_thread.py index c62c15939..1dc1ff069 100644 --- a/src/tests/test_thread.py +++ b/src/tests/test_thread.py @@ -5,7 +5,7 @@ import threading import time -from ._compat import range, thread +from ._compat import thread from .utils import dprint diff --git a/src/tests/utils.py b/src/tests/utils.py index cacb015ec..3bf6e8763 100644 --- a/src/tests/utils.py +++ b/src/tests/utils.py @@ -7,9 +7,6 @@ from __future__ import print_function -from ._compat import PY2, PY3 - - def dprint(msg): # Debugging helper to trace thread-related tests. if 0: @@ -21,11 +18,8 @@ def is_clr_module(ob): def is_clr_root_module(ob): - if PY3: - # in Python 3 the clr module is a normal python module - return ob.__name__ == "clr" - elif PY2: - return type(ob).__name__ == 'CLRModule' + # in Python 3 the clr module is a normal python module + return ob.__name__ == "clr" def is_clr_class(ob): From 048219daec960326679050e3e4e8ac5d9085e699 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Sun, 14 Jun 2020 17:02:45 +0200 Subject: [PATCH 3/8] Drop a few more references to the version and fix build on Windows --- setup.py | 3 ++ src/embed_tests/TestPythonEngineProperties.cs | 26 ---------------- src/runtime/runtime.cs | 30 +++++-------------- 3 files changed, 11 insertions(+), 48 deletions(-) diff --git a/setup.py b/setup.py index 9d21c7038..e1b2901c3 100644 --- a/setup.py +++ b/setup.py @@ -281,6 +281,9 @@ def build_extension(self, ext): if not enable_shared: defines.append("PYTHON_WITHOUT_ENABLE_SHARED") + else: + defines.append("WINDOWS") + if hasattr(sys, "abiflags"): if "d" in sys.abiflags: defines.append("PYTHON_WITH_PYDEBUG") diff --git a/src/embed_tests/TestPythonEngineProperties.cs b/src/embed_tests/TestPythonEngineProperties.cs index 243349b82..6d2d5d6cc 100644 --- a/src/embed_tests/TestPythonEngineProperties.cs +++ b/src/embed_tests/TestPythonEngineProperties.cs @@ -180,12 +180,6 @@ public void SetProgramName() [Test] public void SetPythonPath() { - if (Runtime.Runtime.pyversion == "2.7") - { - // Assert.Skip outputs as a warning (ie. pending to fix) - Assert.Pass(); - } - PythonEngine.Initialize(); string path = PythonEngine.PythonPath; PythonEngine.Shutdown(); @@ -196,25 +190,5 @@ public void SetPythonPath() Assert.AreEqual(path, PythonEngine.PythonPath); PythonEngine.Shutdown(); } - - [Test] - public void SetPythonPathExceptionOn27() - { - if (Runtime.Runtime.pyversion != "2.7") - { - Assert.Pass(); - } - - PythonEngine.Initialize(); - string path = PythonEngine.PythonPath; - PythonEngine.Shutdown(); - - var ex = Assert.Throws(() => PythonEngine.PythonPath = "foo"); - Assert.AreEqual("Set PythonPath not supported on Python 2", ex.Message); - - PythonEngine.Initialize(); - Assert.AreEqual(path, PythonEngine.PythonPath); - PythonEngine.Shutdown(); - } } } diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 84f5a997e..03adbc024 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -43,36 +43,24 @@ public class Runtime #error You must define either UCS2 or UCS4! #endif - // C# compiler copies constants to the assemblies that references this library. - // We needs to replace all public constants to static readonly fields to allow - // binary substitution of different Python.Runtime.dll builds in a target application. - - public static string pyversion => _pyversion; - public static string pyver => _pyver; - #if PYTHON34 - internal const string _pyversion = "3.4"; - internal const string _pyver = "34"; + const string _minor = "4"; #elif PYTHON35 - internal const string _pyversion = "3.5"; - internal const string _pyver = "35"; + const string _minor = "5"; #elif PYTHON36 - internal const string _pyversion = "3.6"; - internal const string _pyver = "36"; + const string _minor = "6"; #elif PYTHON37 - internal const string _pyversion = "3.7"; - internal const string _pyver = "37"; + const string _minor = "7"; #elif PYTHON38 - internal const string _pyversion = "3.8"; - internal const string _pyver = "38"; + const string _minor = "8"; #else #error You must define one of PYTHON34 to PYTHON38 #endif -#if MONO_LINUX || MONO_OSX // Linux/macOS use dotted version string - internal const string dllBase = "python" + _pyversion; +#if !WINDOWS + internal const string dllBase = "python3" + _minor; #else // Windows - internal const string dllBase = "python" + _pyver; + internal const string dllBase = "python3." + _minor; #endif #if PYTHON_WITH_PYDEBUG @@ -98,8 +86,6 @@ public class Runtime internal const string _PythonDll = dllBase + dllWithPyDebug + dllWithPyMalloc; #endif - public static readonly int pyversionnumber = Convert.ToInt32(_pyver); - // set to true when python is finalizing internal static object IsFinalizingLock = new object(); internal static bool IsFinalizing; From aad04272acf74e8338d56505fb54ab01209956a5 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Sun, 14 Jun 2020 17:07:20 +0200 Subject: [PATCH 4/8] Drop accidentally committed interop --- src/runtime/interop37m.cs | 150 -------------------------------------- 1 file changed, 150 deletions(-) delete mode 100644 src/runtime/interop37m.cs diff --git a/src/runtime/interop37m.cs b/src/runtime/interop37m.cs deleted file mode 100644 index 42e8e0f31..000000000 --- a/src/runtime/interop37m.cs +++ /dev/null @@ -1,150 +0,0 @@ - -// Auto-generated by geninterop.py. -// DO NOT MODIFY BY HAND. - - -#if PYTHON37 && PYTHON_WITH_PYMALLOC -using System; -using System.Collections; -using System.Collections.Specialized; -using System.Runtime.InteropServices; -using System.Reflection; -using System.Text; - -namespace Python.Runtime -{ - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] - internal class TypeOffset - { - static TypeOffset() - { - Type type = typeof(TypeOffset); - FieldInfo[] fi = type.GetFields(); - int size = IntPtr.Size; - for (int i = 0; i < fi.Length; i++) - { - fi[i].SetValue(null, i * size); - } - } - - public static int magic() - { - return ob_size; - } - - // Auto-generated from PyHeapTypeObject in Python.h - public static int ob_refcnt = 0; - public static int ob_type = 0; - public static int ob_size = 0; - public static int tp_name = 0; - public static int tp_basicsize = 0; - public static int tp_itemsize = 0; - public static int tp_dealloc = 0; - public static int tp_print = 0; - public static int tp_getattr = 0; - public static int tp_setattr = 0; - public static int tp_as_async = 0; - public static int tp_repr = 0; - public static int tp_as_number = 0; - public static int tp_as_sequence = 0; - public static int tp_as_mapping = 0; - public static int tp_hash = 0; - public static int tp_call = 0; - public static int tp_str = 0; - public static int tp_getattro = 0; - public static int tp_setattro = 0; - public static int tp_as_buffer = 0; - public static int tp_flags = 0; - public static int tp_doc = 0; - public static int tp_traverse = 0; - public static int tp_clear = 0; - public static int tp_richcompare = 0; - public static int tp_weaklistoffset = 0; - public static int tp_iter = 0; - public static int tp_iternext = 0; - public static int tp_methods = 0; - public static int tp_members = 0; - public static int tp_getset = 0; - public static int tp_base = 0; - public static int tp_dict = 0; - public static int tp_descr_get = 0; - public static int tp_descr_set = 0; - public static int tp_dictoffset = 0; - public static int tp_init = 0; - public static int tp_alloc = 0; - public static int tp_new = 0; - public static int tp_free = 0; - public static int tp_is_gc = 0; - public static int tp_bases = 0; - public static int tp_mro = 0; - public static int tp_cache = 0; - public static int tp_subclasses = 0; - public static int tp_weaklist = 0; - public static int tp_del = 0; - public static int tp_version_tag = 0; - public static int tp_finalize = 0; - public static int am_await = 0; - public static int am_aiter = 0; - public static int am_anext = 0; - public static int nb_add = 0; - public static int nb_subtract = 0; - public static int nb_multiply = 0; - public static int nb_remainder = 0; - public static int nb_divmod = 0; - public static int nb_power = 0; - public static int nb_negative = 0; - public static int nb_positive = 0; - public static int nb_absolute = 0; - public static int nb_bool = 0; - public static int nb_invert = 0; - public static int nb_lshift = 0; - public static int nb_rshift = 0; - public static int nb_and = 0; - public static int nb_xor = 0; - public static int nb_or = 0; - public static int nb_int = 0; - public static int nb_reserved = 0; - public static int nb_float = 0; - public static int nb_inplace_add = 0; - public static int nb_inplace_subtract = 0; - public static int nb_inplace_multiply = 0; - public static int nb_inplace_remainder = 0; - public static int nb_inplace_power = 0; - public static int nb_inplace_lshift = 0; - public static int nb_inplace_rshift = 0; - public static int nb_inplace_and = 0; - public static int nb_inplace_xor = 0; - public static int nb_inplace_or = 0; - public static int nb_floor_divide = 0; - public static int nb_true_divide = 0; - public static int nb_inplace_floor_divide = 0; - public static int nb_inplace_true_divide = 0; - public static int nb_index = 0; - public static int nb_matrix_multiply = 0; - public static int nb_inplace_matrix_multiply = 0; - public static int mp_length = 0; - public static int mp_subscript = 0; - public static int mp_ass_subscript = 0; - public static int sq_length = 0; - public static int sq_concat = 0; - public static int sq_repeat = 0; - public static int sq_item = 0; - public static int was_sq_slice = 0; - public static int sq_ass_item = 0; - public static int was_sq_ass_slice = 0; - public static int sq_contains = 0; - public static int sq_inplace_concat = 0; - public static int sq_inplace_repeat = 0; - public static int bf_getbuffer = 0; - public static int bf_releasebuffer = 0; - public static int name = 0; - public static int ht_slots = 0; - public static int qualname = 0; - public static int ht_cached_keys = 0; - - /* here are optional user slots, followed by the members. */ - public static int members = 0; - } -} - -#endif From e1d60347607dfc4a0d1dda09045016a9a326523b Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Sun, 14 Jun 2020 20:24:28 +0200 Subject: [PATCH 5/8] Fix the dotted/undotted logic --- setup.py | 2 +- src/runtime/runtime.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index e1b2901c3..5aa94f6c5 100644 --- a/setup.py +++ b/setup.py @@ -281,7 +281,7 @@ def build_extension(self, ext): if not enable_shared: defines.append("PYTHON_WITHOUT_ENABLE_SHARED") - else: + if sys.platform == "win32": defines.append("WINDOWS") if hasattr(sys, "abiflags"): diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 03adbc024..f63b1feae 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -57,9 +57,9 @@ public class Runtime #error You must define one of PYTHON34 to PYTHON38 #endif -#if !WINDOWS +#if WINDOWS internal const string dllBase = "python3" + _minor; -#else // Windows +#else internal const string dllBase = "python3." + _minor; #endif From d19b81335e64b685711dbb08429975fd2afaf2ea Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Fri, 19 Jun 2020 08:46:20 +0200 Subject: [PATCH 6/8] Fix a few more tests --- src/tests/test_conversion.py | 9 ++++----- src/tests/test_generic.py | 2 +- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/tests/test_conversion.py b/src/tests/test_conversion.py index 6a4698157..74613abd1 100644 --- a/src/tests/test_conversion.py +++ b/src/tests/test_conversion.py @@ -1,10 +1,9 @@ -# -*- coding: utf-8 -*- - """Test CLR <-> Python type conversions.""" -from __future__ import unicode_literals -import System +import operator import pytest + +import System from Python.Test import ConversionTest, UnicodeString from Python.Runtime import PyObjectConversions from Python.Runtime.Codecs import RawProxyEncoder @@ -541,7 +540,7 @@ def test_string_conversion(): test_unicode_str = u"안녕" assert test_unicode_str == str(world.value) assert test_unicode_str == str(world.GetString()) - assert test_unicode_str == (world) + assert test_unicode_str == str(world) def test_interface_conversion(): diff --git a/src/tests/test_generic.py b/src/tests/test_generic.py index fc40e8e43..9c410271d 100644 --- a/src/tests/test_generic.py +++ b/src/tests/test_generic.py @@ -135,7 +135,7 @@ def test_python_type_aliasing(): dict_.Add(1, 1) assert dict_[1] == 1 - dict_ = Dictionary[long, long]() + dict_ = Dictionary[int, int]() assert dict_.Count == 0 dict_.Add(1, 1) assert dict_[1] == 1 From 6dc74714df3fca3f1705064ac8cb09a442a97ab6 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Fri, 19 Jun 2020 16:58:01 +0200 Subject: [PATCH 7/8] Drop more Python 2 checks --- setup.py | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/setup.py b/setup.py index 5aa94f6c5..ca4f49a63 100644 --- a/setup.py +++ b/setup.py @@ -150,8 +150,6 @@ def _check_output(*args, **kwargs): """Check output wrapper for py2/py3 compatibility""" output = subprocess.check_output(*args, **kwargs) - if PY_MAJOR == 2: - return output return output.decode("ascii") @@ -475,10 +473,7 @@ def _find_msbuild_tool(self, tool="msbuild.exe", use_windows_sdk=False): return path # Search within registry to find build tools - try: # PY2 - import _winreg as winreg - except ImportError: # PY3 - import winreg + import winreg _collect_installed_windows_kits_v10(winreg) From cc4211c27af7bf79f8f457f2430b8688ac03c52e Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Fri, 19 Jun 2020 23:10:27 +0200 Subject: [PATCH 8/8] Drop tests._compat module entirely --- src/tests/_compat.py | 15 --------------- src/tests/stress.py | 2 +- src/tests/test_class.py | 2 +- src/tests/test_delegate.py | 3 +-- src/tests/test_enum.py | 2 +- src/tests/test_exceptions.py | 1 - src/tests/test_interface.py | 2 +- src/tests/test_sysargv.py | 9 +++------ src/tests/test_thread.py | 2 +- src/tests/tests.pyproj | 1 - src/tests/utils.py | 3 ++- 11 files changed, 11 insertions(+), 31 deletions(-) delete mode 100644 src/tests/_compat.py diff --git a/src/tests/_compat.py b/src/tests/_compat.py deleted file mode 100644 index f44ca4649..000000000 --- a/src/tests/_compat.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- - -"""Python 2.7, 3.3+ compatibility module. - -Using Python 3 syntax to encourage upgrade unless otherwise noted. -""" - -import subprocess -import _thread as thread -DictProxyType = type(object.__dict__) - -def check_output(*args, **kwargs): - """Check output wrapper for PY2/PY3 compatibility""" - output = subprocess.check_output(*args, **kwargs) - return output.decode("ascii") diff --git a/src/tests/stress.py b/src/tests/stress.py index b5a67b124..f1f0fac6b 100644 --- a/src/tests/stress.py +++ b/src/tests/stress.py @@ -17,7 +17,7 @@ import threading import time -from ._compat import thread +import _thread as thread from .utils import dprint diff --git a/src/tests/test_class.py b/src/tests/test_class.py index ecc8b56fb..2f15f35b1 100644 --- a/src/tests/test_class.py +++ b/src/tests/test_class.py @@ -7,7 +7,7 @@ import System import pytest -from ._compat import DictProxyType +from .utils import DictProxyType def test_basic_reference_type(): diff --git a/src/tests/test_delegate.py b/src/tests/test_delegate.py index 33aca43b3..1bfc4e903 100644 --- a/src/tests/test_delegate.py +++ b/src/tests/test_delegate.py @@ -8,8 +8,7 @@ import pytest from Python.Test import DelegateTest, StringDelegate -from ._compat import DictProxyType -from .utils import HelloClass, hello_func, MultipleHandler +from .utils import HelloClass, hello_func, MultipleHandler, DictProxyType def test_delegate_standard_attrs(): diff --git a/src/tests/test_enum.py b/src/tests/test_enum.py index 7ca816eec..27fe7e9ef 100644 --- a/src/tests/test_enum.py +++ b/src/tests/test_enum.py @@ -5,7 +5,7 @@ import pytest import Python.Test as Test -from ._compat import DictProxyType +from .utils import DictProxyType def test_enum_standard_attrs(): diff --git a/src/tests/test_exceptions.py b/src/tests/test_exceptions.py index 842f35bca..02d3005aa 100644 --- a/src/tests/test_exceptions.py +++ b/src/tests/test_exceptions.py @@ -277,7 +277,6 @@ def test_python_compat_of_managed_exceptions(): e = OverflowException(msg) assert str(e) == msg - assert str(e) == msg assert e.args == (msg,) assert isinstance(e.args, tuple) diff --git a/src/tests/test_interface.py b/src/tests/test_interface.py index 997f17264..6b72c1a12 100644 --- a/src/tests/test_interface.py +++ b/src/tests/test_interface.py @@ -5,7 +5,7 @@ import Python.Test as Test import pytest -from ._compat import DictProxyType +from .utils import DictProxyType def test_interface_standard_attrs(): diff --git a/src/tests/test_sysargv.py b/src/tests/test_sysargv.py index d86aa1c1d..dd62bc632 100644 --- a/src/tests/test_sysargv.py +++ b/src/tests/test_sysargv.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- - """Test sys.argv state.""" import sys - -from ._compat import check_output +from subprocess import check_output def test_sys_argv_state(filepath): @@ -14,5 +11,5 @@ def test_sys_argv_state(filepath): script = filepath("argv-fixture.py") out = check_output([sys.executable, script, "foo", "bar"]) - assert "foo" in out - assert "bar" in out + assert b"foo" in out + assert b"bar" in out diff --git a/src/tests/test_thread.py b/src/tests/test_thread.py index 1dc1ff069..909c71f1c 100644 --- a/src/tests/test_thread.py +++ b/src/tests/test_thread.py @@ -5,7 +5,7 @@ import threading import time -from ._compat import thread +import _thread as thread from .utils import dprint diff --git a/src/tests/tests.pyproj b/src/tests/tests.pyproj index 074792e43..4bdbc6b14 100644 --- a/src/tests/tests.pyproj +++ b/src/tests/tests.pyproj @@ -28,7 +28,6 @@ - diff --git a/src/tests/utils.py b/src/tests/utils.py index 3bf6e8763..b467cae97 100644 --- a/src/tests/utils.py +++ b/src/tests/utils.py @@ -5,7 +5,8 @@ Refactor utility functions and classes """ -from __future__ import print_function +DictProxyType = type(object.__dict__) + def dprint(msg): # Debugging helper to trace thread-related tests. pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy