From 98cbe2b3ace53ef70738345548402cb4e74a4db7 Mon Sep 17 00:00:00 2001 From: Simon McVittie Date: Tue, 14 Sep 2021 16:48:18 +0100 Subject: Remove support for Python 2 Python 2 reached EOL on 2020-01-01, and the latest version of AX_PYTHON_DEVEL breaks the build with Python 2. This seems as good a time as any to drop compatibility. Signed-off-by: Simon McVittie --- .gitlab-ci.yml | 19 +-- Makefile.am | 13 +-- configure.ac | 14 +-- dbus/__init__.py | 5 - dbus/_compat.py | 10 +- dbus/_dbus.py | 3 - dbus/bus.py | 21 +--- dbus/connection.py | 34 ++---- dbus/decorators.py | 5 +- dbus/exceptions.py | 5 +- dbus/gobject_service.py | 88 -------------- dbus/proxies.py | 2 - dbus/service.py | 3 - dbus/types.py | 3 - dbus_bindings/abstract.c | 204 +++------------------------------ dbus_bindings/bus.c | 12 +- dbus_bindings/bytes.c | 38 ++---- dbus_bindings/conn-methods.c | 4 +- dbus_bindings/conn.c | 4 - dbus_bindings/containers.c | 52 +-------- dbus_bindings/dbus_bindings-internal.h | 26 ----- dbus_bindings/exceptions.c | 4 +- dbus_bindings/float.c | 6 - dbus_bindings/int.c | 71 +++--------- dbus_bindings/message-append.c | 127 +++++--------------- dbus_bindings/message-get-args.c | 54 ++------- dbus_bindings/message.c | 14 +-- dbus_bindings/module.c | 20 ---- dbus_bindings/server.c | 8 +- dbus_bindings/signature.c | 8 -- dbus_bindings/string.c | 114 ------------------ dbus_bindings/types-internal.h | 17 --- dbus_bindings/unixfd.c | 2 +- dbus_glib_bindings/module.c | 17 --- include/dbus/dbus-python.h | 15 --- test/cross-test-client.py | 16 +-- test/cross-test-server.py | 17 +-- test/dbus_py_test.c | 16 --- test/test-client.py | 49 +------- test/test-exception-py2.py | 65 ----------- test/test-p2p.py | 15 +-- test/test-service.py | 9 +- test/test-standalone.py | 103 +++-------------- tools/ci-build.sh | 13 +-- tools/ci-install.sh | 29 ++--- 45 files changed, 164 insertions(+), 1210 deletions(-) delete mode 100644 dbus/gobject_service.py delete mode 100755 test/test-exception-py2.py diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index d3a3214..a294814 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -36,27 +36,15 @@ variables: ci_distro: "debian" ci_suite: "buster" -build:python2.7: - stage: build - variables: - dbus_ci_system_python: python - script: &script - - chown -R user . - - runuser -u user -- env PATH="/usr/lib/ccache:$PATH" ./tools/ci-build.sh $dbus_ci_configure_flags - -build:python2.7-dbg: - stage: build - variables: - dbus_ci_system_python: python-dbg - script: *script - build:python3.5: stage: build image: "debian:stretch-slim" variables: ci_suite: stretch dbus_ci_system_python: python3 - script: *script + script: &script + - chown -R user . + - runuser -u user -- env PATH="/usr/lib/ccache:$PATH" ./tools/ci-build.sh $dbus_ci_configure_flags build:python3.5-dbg: stage: build @@ -92,7 +80,6 @@ build:python3.9-dbg: variables: ci_suite: bullseye dbus_ci_system_python: python3.9-dbg - dbus_ci_system_python_module_prefix: python3- dbus_ci_system_python_module_suffix: -dbg script: *script diff --git a/Makefile.am b/Makefile.am index fb5390f..77c65ca 100644 --- a/Makefile.am +++ b/Makefile.am @@ -175,12 +175,6 @@ nobase_python_PYTHON = \ dbus/service.py \ dbus/types.py -if !HAVE_PYTHON_3 -nobase_python_PYTHON += \ - dbus/gobject_service.py \ - $(NULL) -endif - check_py_sources = $(nobase_python_PYTHON) include $(top_srcdir)/tools/check-coding-style.mk @@ -241,6 +235,7 @@ dist_test_sh = \ dist_test_py = \ test/test-client.py \ + test/test-exception-py3.py \ test/test-p2p.py \ test/test-signals.py \ test/test-standalone.py \ @@ -259,12 +254,6 @@ dist_test_extra_scripts = \ test/wait-for-name.py \ $(NULL) -if HAVE_PYTHON_3 -dist_test_py += test/test-exception-py3.py -else -dist_test_py += test/test-exception-py2.py -endif - test_programs = \ test/test-import-repeatedly \ $(NULL) diff --git a/configure.ac b/configure.ac index b1d301c..e87b099 100644 --- a/configure.ac +++ b/configure.ac @@ -81,19 +81,7 @@ AS_IF([test -z "$PYTHON_VERSION" && test -z "$PYTHON"], [PYTHON_VERSION=3]) AX_PYTHON_DEVEL([>= '2.7']) AM_PATH_PYTHON -# This command exits 0 (success) if sys.version >= "3", or 1 (failure) -# if sys.version < "3" (i.e. starts with "2"). -AM_CONDITIONAL([HAVE_PYTHON_3], - [$PYTHON -c "import sys; sys.exit(sys.version < '3')"]) - -PLATFORM=`$PYTHON -c " -from __future__ import print_function -try: - import sysconfig -except ImportError: - from distutils import util as sysconfig -print(sysconfig.get_platform()) -"` +PLATFORM=`$PYTHON -c "import sysconfig; print(sysconfig.get_platform())"` AC_SUBST(PLATFORM) AC_ARG_ENABLE([installed-tests], diff --git a/dbus/__init__.py b/dbus/__init__.py index e5133c0..8cf3989 100644 --- a/dbus/__init__.py +++ b/dbus/__init__.py @@ -63,8 +63,6 @@ __all__ = [ ] from dbus._compat import is_py2 -if is_py2: - __all__.append('UTF8String') __docformat__ = 'restructuredtext' @@ -91,8 +89,5 @@ from _dbus_bindings import ( Array, Boolean, Byte, ByteArray, Dictionary, Double, Int16, Int32, Int64, ObjectPath, Signature, String, Struct, UInt16, UInt32, UInt64) -if is_py2: - from _dbus_bindings import UTF8String - from dbus._dbus import Bus, SystemBus, SessionBus, StarterBus from dbus.proxies import Interface diff --git a/dbus/_compat.py b/dbus/_compat.py index 5417ae8..ea242a3 100644 --- a/dbus/_compat.py +++ b/dbus/_compat.py @@ -3,5 +3,11 @@ import sys -is_py3 = (sys.version_info.major == 3) -is_py2 = not is_py3 +is_py3 = True +is_py2 = False + +if sys.version_info.major < 3: + raise AssertionError( + 'Python 2 has reached end-of-life, and dbus-python no longer ' + 'supports it.' + ) diff --git a/dbus/_dbus.py b/dbus/_dbus.py index 4b0b37a..2891194 100644 --- a/dbus/_dbus.py +++ b/dbus/_dbus.py @@ -42,9 +42,6 @@ from dbus.bus import BusConnection from dbus.lowlevel import SignalMessage from dbus._compat import is_py2 -if is_py2: - from _dbus_bindings import UTF8String - class Bus(BusConnection): """A connection to one of three possible standard buses, the SESSION, diff --git a/dbus/bus.py b/dbus/bus.py index 6222862..fd5a281 100644 --- a/dbus/bus.py +++ b/dbus/bus.py @@ -80,16 +80,12 @@ class NameOwnerWatch(object): BUS_DAEMON_NAME, BUS_DAEMON_PATH, arg0=bus_name) - keywords = {} - if is_py2: - keywords['utf8_strings'] = True self._pending_call = bus_conn.call_async(BUS_DAEMON_NAME, BUS_DAEMON_PATH, BUS_DAEMON_IFACE, 'GetNameOwner', 's', (bus_name,), - callback, error_cb, - **keywords) + callback, error_cb) def cancel(self): if self._match is not None: @@ -327,12 +323,9 @@ class BusConnection(Connection): :Returns: a dbus.Array of dbus.UTF8String :Since: 0.81.0 """ - keywords = {} - if is_py2: - keywords['utf8_strings'] = True return self.call_blocking(BUS_DAEMON_NAME, BUS_DAEMON_PATH, BUS_DAEMON_IFACE, 'ListNames', - '', (), **keywords) + '', ()) def list_activatable_names(self): """Return a list of all names that can be activated on the bus. @@ -340,12 +333,9 @@ class BusConnection(Connection): :Returns: a dbus.Array of dbus.UTF8String :Since: 0.81.0 """ - keywords = {} - if is_py2: - keywords['utf8_strings'] = True return self.call_blocking(BUS_DAEMON_NAME, BUS_DAEMON_PATH, BUS_DAEMON_IFACE, 'ListActivatableNames', - '', (), **keywords) + '', ()) def get_name_owner(self, bus_name): """Return the unique connection name of the primary owner of the @@ -354,13 +344,10 @@ class BusConnection(Connection): :Raises `DBusException`: if the `bus_name` has no owner :Since: 0.81.0 """ - keywords = {} - if is_py2: - keywords['utf8_strings'] = True validate_bus_name(bus_name, allow_unique=False) return self.call_blocking(BUS_DAEMON_NAME, BUS_DAEMON_PATH, BUS_DAEMON_IFACE, 'GetNameOwner', - 's', (bus_name,), **keywords) + 's', (bus_name,)) def watch_name_owner(self, bus_name, callback): """Watch the unique connection name of the primary owner of the diff --git a/dbus/connection.py b/dbus/connection.py index f5c8dd9..daabfc2 100644 --- a/dbus/connection.py +++ b/dbus/connection.py @@ -39,10 +39,7 @@ from dbus.lowlevel import ( from dbus.proxies import ProxyObject from dbus._compat import is_py2, is_py3 -if is_py3: - from _dbus_bindings import String -else: - from _dbus_bindings import UTF8String +from _dbus_bindings import String _logger = logging.getLogger('dbus.connection') @@ -59,8 +56,6 @@ class SignalMatch(object): '_destination_keyword', '_interface_keyword', '_message_keyword', '_member_keyword', '_sender_keyword', '_path_keyword', '_int_args_match'] - if is_py2: - _slots.append('_utf8_strings') __slots__ = tuple(_slots) @@ -91,9 +86,7 @@ class SignalMatch(object): # this later self._sender_name_owner = sender - if is_py2: - self._utf8_strings = kwargs.pop('utf8_strings', False) - elif 'utf8_strings' in kwargs: + if 'utf8_strings' in kwargs: raise TypeError("unexpected keyword argument 'utf8_strings'") self._byte_arrays = byte_arrays @@ -186,15 +179,12 @@ class SignalMatch(object): if self._sender_name_owner not in (None, message.get_sender()): return False if self._int_args_match is not None: - # extracting args with utf8_strings and byte_arrays is less work + # extracting args with byte_arrays is less work kwargs = dict(byte_arrays=True) - arg_type = (String if is_py3 else UTF8String) - if is_py2: - kwargs['utf8_strings'] = True args = message.get_args_list(**kwargs) for index, value in self._int_args_match.items(): if (index >= len(args) - or not isinstance(args[index], arg_type) + or not isinstance(args[index], String) or args[index] != value): return False @@ -210,12 +200,8 @@ class SignalMatch(object): # minor optimization: if we already extracted the args with the # right calling convention to do the args match, don't bother # doing so again - utf8_strings = (is_py2 and self._utf8_strings) - if args is None or not utf8_strings or not self._byte_arrays: - kwargs = dict(byte_arrays=self._byte_arrays) - if is_py2: - kwargs['utf8_strings'] = self._utf8_strings - args = message.get_args_list(**kwargs) + if args is None or not self._byte_arrays: + args = message.get_args_list(byte_arrays=self._byte_arrays) kwargs = {} if self._sender_keyword is not None: kwargs[self._sender_keyword] = message.get_sender() @@ -572,9 +558,7 @@ class Connection(_Connection): # no need to validate other args - MethodCallMessage ctor will do get_args_opts = dict(byte_arrays=byte_arrays) - if is_py2: - get_args_opts['utf8_strings'] = kwargs.get('utf8_strings', False) - elif 'utf8_strings' in kwargs: + if 'utf8_strings' in kwargs: raise TypeError("unexpected keyword argument 'utf8_strings'") message = MethodCallMessage(destination=bus_name, @@ -629,9 +613,7 @@ class Connection(_Connection): # no need to validate other args - MethodCallMessage ctor will do get_args_opts = dict(byte_arrays=byte_arrays) - if is_py2: - get_args_opts['utf8_strings'] = kwargs.get('utf8_strings', False) - elif 'utf8_strings' in kwargs: + if 'utf8_strings' in kwargs: raise TypeError("unexpected keyword argument 'utf8_strings'") message = MethodCallMessage(destination=bus_name, diff --git a/dbus/decorators.py b/dbus/decorators.py index 1676d37..3dc04a6 100644 --- a/dbus/decorators.py +++ b/dbus/decorators.py @@ -211,10 +211,7 @@ def method(dbus_interface, in_signature=None, out_signature=None, func._dbus_connection_keyword = connection_keyword func._dbus_args = args func._dbus_get_args_options = dict(byte_arrays=byte_arrays) - if is_py2: - func._dbus_get_args_options['utf8_strings'] = kwargs.get( - 'utf8_strings', False) - elif 'utf8_strings' in kwargs: + if 'utf8_strings' in kwargs: raise TypeError("unexpected keyword argument 'utf8_strings'") return func diff --git a/dbus/exceptions.py b/dbus/exceptions.py index 6e85a3e..870b731 100644 --- a/dbus/exceptions.py +++ b/dbus/exceptions.py @@ -77,10 +77,7 @@ class DBusException(Exception): def get_dbus_message(self): if len(self.args) > 1: - if is_py3: - s = str(self.args) - else: - s = unicode(self.args) + s = str(self.args) else: s = ''.join(self.args) diff --git a/dbus/gobject_service.py b/dbus/gobject_service.py deleted file mode 100644 index 6124ee5..0000000 --- a/dbus/gobject_service.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Support code for implementing D-Bus services via GObjects.""" - -# Copyright (C) 2007 Collabora Ltd. -# -# SPDX-License-Identifier: MIT -# -# Permission is hereby granted, free of charge, to any person -# obtaining a copy of this software and associated documentation -# files (the "Software"), to deal in the Software without -# restriction, including without limitation the rights to use, copy, -# modify, merge, publish, distribute, sublicense, and/or sell copies -# of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -# DEALINGS IN THE SOFTWARE. - -import sys -from warnings import warn as _warn -_warn(DeprecationWarning("""\ -dbus.gobject_service is deprecated, and is not available under Python 3. - -Porting from gobject (PyGObject 2) to gi.repository.GObject (PyGObject 3), -and using dbus.gi_service instead of dbus.gobject_service, is recommended. -"""), DeprecationWarning, stacklevel=2) - -if 'gi' in sys.modules: - # this worked in dbus-python 1.0, so preserve the functionality - from gi.repository import GObject as gobject -else: - # this worked in dbus-python < 1.0 - import gobject - -import dbus.service - -class ExportedGObjectType(gobject.GObject.__class__, dbus.service.InterfaceType): - """A metaclass which inherits from both GObjectMeta and - `dbus.service.InterfaceType`. Used as the metaclass for `ExportedGObject`. - """ - def __init__(cls, name, bases, dct): - gobject.GObject.__class__.__init__(cls, name, bases, dct) - dbus.service.InterfaceType.__init__(cls, name, bases, dct) - -class ExportedGObject(gobject.GObject, dbus.service.Object): - """A GObject which is exported on the D-Bus. - - Because GObject and `dbus.service.Object` both have custom metaclasses, - the naive approach using simple multiple inheritance won't work. This - class has `ExportedGObjectType` as its metaclass, which is sufficient - to make it work correctly. - """ - __metaclass__ = ExportedGObjectType - - def __init__(self, conn=None, object_path=None, **kwargs): - """Initialize an exported GObject. - - :Parameters: - `conn` : dbus.connection.Connection - The D-Bus connection or bus - `object_path` : str - The object path at which to register this object. - :Keywords: - `bus_name` : dbus.service.BusName - A bus name to be held on behalf of this object, or None. - `gobject_properties` : dict - GObject properties to be set on the constructed object. - - Any unrecognised keyword arguments will also be interpreted - as GObject properties. - """ - bus_name = kwargs.pop('bus_name', None) - gobject_properties = kwargs.pop('gobject_properties', None) - - if gobject_properties is not None: - kwargs.update(gobject_properties) - gobject.GObject.__init__(self, **kwargs) - dbus.service.Object.__init__(self, conn=conn, - object_path=object_path, - bus_name=bus_name) diff --git a/dbus/proxies.py b/dbus/proxies.py index 5852046..8489294 100644 --- a/dbus/proxies.py +++ b/dbus/proxies.py @@ -372,8 +372,6 @@ class ProxyObject(object): def _Introspect(self): kwargs = {} - if is_py2: - kwargs['utf8_strings'] = True return self._bus.call_async(self._named_service, self.__dbus_object_path__, INTROSPECTABLE_IFACE, 'Introspect', '', (), diff --git a/dbus/service.py b/dbus/service.py index 0c8695a..2e13d3c 100644 --- a/dbus/service.py +++ b/dbus/service.py @@ -67,9 +67,6 @@ class _VariantSignature(object): """Return 'v' whenever called.""" return 'v' - if is_py2: - next = __next__ - class BusName(object): """A base class for exporting your own Named Services across the Bus. diff --git a/dbus/types.py b/dbus/types.py index d0b9683..849ffdc 100644 --- a/dbus/types.py +++ b/dbus/types.py @@ -11,6 +11,3 @@ from _dbus_bindings import ( UnixFd) from dbus._compat import is_py2 -if is_py2: - from _dbus_bindings import UTF8String - __all__.append('UTF8String') diff --git a/dbus_bindings/abstract.c b/dbus_bindings/abstract.c index 4eca52a..64ac9fb 100644 --- a/dbus_bindings/abstract.c +++ b/dbus_bindings/abstract.c @@ -62,7 +62,7 @@ dbus_py_variant_level_get(PyObject *obj) */ return 0; } - variant_level = NATIVEINT_ASLONG(vl_obj); + variant_level = PyLong_AsLong(vl_obj); if (variant_level == -1 && PyErr_Occurred()) { /* variant_level < 0 can never be inserted into the dictionary; see * dbus_py_variant_level_set() below. The semantics of setting @@ -93,7 +93,7 @@ dbus_py_variant_level_set(PyObject *obj, long variant_level) } } else { - PyObject *vl_obj = NATIVEINT_FROMLONG(variant_level); + PyObject *vl_obj = PyLong_FromLong(variant_level); if (!vl_obj) { Py_CLEAR(key); return FALSE; @@ -114,32 +114,8 @@ dbus_py_variant_level_getattro(PyObject *obj, PyObject *name) { PyObject *key, *value; -#ifdef PY3 if (PyUnicode_CompareWithASCIIString(name, "variant_level")) return PyObject_GenericGetAttr(obj, name); -#else - if (PyBytes_Check(name)) { - Py_INCREF(name); - } - else if (PyUnicode_Check(name)) { - name = PyUnicode_AsEncodedString(name, NULL, NULL); - if (!name) { - return NULL; - } - } - else { - PyErr_SetString(PyExc_TypeError, "attribute name must be string"); - return NULL; - } - - if (strcmp(PyBytes_AS_STRING(name), "variant_level")) { - value = PyObject_GenericGetAttr(obj, name); - Py_CLEAR(name); - return value; - } - - Py_CLEAR(name); -#endif /* PY3 */ key = PyLong_FromVoidPtr(obj); @@ -151,7 +127,7 @@ dbus_py_variant_level_getattro(PyObject *obj, PyObject *name) Py_CLEAR(key); if (!value) - return NATIVEINT_FROMLONG(0); + return PyLong_FromLong(0); Py_INCREF(value); return value; } @@ -172,122 +148,11 @@ dbus_py_variant_level_clear(PyObject *self) PyErr_Restore(et, ev, etb); } -#ifndef PY3 -/* Support code for int subclasses. ================================== */ - -PyDoc_STRVAR(DBusPythonInt_tp_doc,\ -"Base class for int subclasses with a ``variant_level`` attribute.\n" -"Do not rely on the existence of this class outside dbus-python.\n" -); - -static PyMemberDef DBusPythonInt_tp_members[] = { - {"variant_level", T_LONG, offsetof(DBusPyIntBase, variant_level), - READONLY, - "The number of nested variants wrapping the real data. " - "0 if not in a variant."}, - {NULL}, -}; - -static PyObject * -DBusPythonInt_tp_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs) -{ - PyObject *self; - long variantness = 0; - static char *argnames[] = {"variant_level", NULL}; - - if (PyTuple_Size(args) > 1) { - PyErr_SetString(PyExc_TypeError, - "__new__ takes at most one positional parameter"); - return NULL; - } - if (!PyArg_ParseTupleAndKeywords(dbus_py_empty_tuple, kwargs, - "|l:__new__", argnames, - &variantness)) return NULL; - if (variantness < 0) { - PyErr_SetString(PyExc_ValueError, - "variant_level must be non-negative"); - return NULL; - } - - self = (PyInt_Type.tp_new)(cls, args, NULL); - if (self) { - ((DBusPyIntBase *)self)->variant_level = variantness; - } - return self; -} - -static PyObject * -DBusPythonInt_tp_repr(PyObject *self) -{ - PyObject *parent_repr = (PyInt_Type.tp_repr)(self); - long variant_level = ((DBusPyIntBase *)self)->variant_level; - PyObject *my_repr; - - if (!parent_repr) return NULL; - if (variant_level > 0) { - my_repr = PyUnicode_FromFormat("%s(%V, variant_level=%ld)", - Py_TYPE(self)->tp_name, - REPRV(parent_repr), - variant_level); - } - else { - my_repr = PyUnicode_FromFormat("%s(%V)", Py_TYPE(self)->tp_name, - REPRV(parent_repr)); - } - /* whether my_repr is NULL or not: */ - Py_CLEAR(parent_repr); - return my_repr; -} - -PyTypeObject DBusPyIntBase_Type = { - PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) - "_dbus_bindings._IntBase", - sizeof(DBusPyIntBase), - 0, - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - DBusPythonInt_tp_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - DBusPythonInt_tp_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - DBusPythonInt_tp_members, /* tp_members */ - 0, /* tp_getset */ - DEFERRED_ADDRESS(&PyInt_Type), /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - DBusPythonInt_tp_new, /* tp_new */ - PyObject_Del, /* tp_free */ -}; -#endif /* !PY3 */ - /* Support code for float subclasses. ================================ */ /* There's only one subclass at the moment (Double) but these are factored out to make room for Float later. (Float is implemented and #if'd out) */ -#ifdef PY3 /* In Python >= 3.8 the tp_str for subclasses of built-in types prints * the subclass repr(), which does not match dbus-python's historical * behaviour. */ @@ -296,9 +161,6 @@ DBusPythonFloat_tp_str(PyObject *self) { return (PyFloat_Type.tp_repr)(self); } -#else -#define DBusPythonFloat_tp_str 0 -#endif PyDoc_STRVAR(DBusPythonFloat_tp_doc,\ "Base class for float subclasses with a ``variant_level`` attribute.\n" @@ -405,7 +267,6 @@ PyTypeObject DBusPyFloatBase_Type = { DBusPythonFloat_tp_new, /* tp_new */ }; -#ifdef PY3 /* Support code for bytes subclasses ================================== */ PyDoc_STRVAR(DBusPythonBytes_tp_doc,\ @@ -460,7 +321,7 @@ DBusPythonBytes_tp_repr(PyObject *self) Py_CLEAR(parent_repr); return NULL; } - variant_level = NATIVEINT_ASLONG(vl_obj); + variant_level = PyLong_AsLong(vl_obj); Py_CLEAR(vl_obj); if (variant_level == -1 && PyErr_Occurred()) { Py_CLEAR(parent_repr); @@ -528,7 +389,6 @@ PyTypeObject DBusPyBytesBase_Type = { 0, /* tp_alloc */ DBusPythonBytes_tp_new, /* tp_new */ }; -#endif /* PY3 */ /* Support code for str subclasses ================================== */ @@ -558,7 +418,7 @@ DBusPythonString_tp_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs) return NULL; } - self = (NATIVESTR_TYPE.tp_new)(cls, args, NULL); + self = (PyUnicode_Type.tp_new)(cls, args, NULL); if (self) { if (!dbus_py_variant_level_set(self, variantness)) { Py_CLEAR(self); @@ -571,7 +431,7 @@ DBusPythonString_tp_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs) static PyObject * DBusPythonString_tp_repr(PyObject *self) { - PyObject *parent_repr = (NATIVESTR_TYPE.tp_repr)(self); + PyObject *parent_repr = (PyUnicode_Type.tp_repr)(self); PyObject *vl_obj; PyObject *my_repr; long variant_level; @@ -582,7 +442,7 @@ DBusPythonString_tp_repr(PyObject *self) Py_CLEAR(parent_repr); return NULL; } - variant_level = NATIVEINT_ASLONG(vl_obj); + variant_level = PyLong_AsLong(vl_obj); Py_CLEAR(vl_obj); if (variant_level == -1 && PyErr_Occurred()) { Py_CLEAR(parent_repr); @@ -608,7 +468,7 @@ static void DBusPyStrBase_tp_dealloc(PyObject *self) { dbus_py_variant_level_clear(self); - (NATIVESTR_TYPE.tp_dealloc)(self); + (PyUnicode_Type.tp_dealloc)(self); } PyTypeObject DBusPyStrBase_Type = { @@ -642,7 +502,7 @@ PyTypeObject DBusPyStrBase_Type = { 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ - DEFERRED_ADDRESS(&NATIVESTR_TYPE), /* tp_base */ + DEFERRED_ADDRESS(&PyUnicode_Type), /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ @@ -704,7 +564,7 @@ DBusPythonLong_tp_repr(PyObject *self) Py_CLEAR(parent_repr); return NULL; } - variant_level = NATIVEINT_ASLONG(vl_obj); + variant_level = PyLong_AsLong(vl_obj); Py_CLEAR(vl_obj); if (variant_level < 0 && PyErr_Occurred()) { Py_CLEAR(parent_repr); @@ -726,7 +586,6 @@ DBusPythonLong_tp_repr(PyObject *self) return my_repr; } -#ifdef PY3 /* In Python >= 3.8 the tp_str for subclasses of built-in types prints * the subclass repr(), which does not match dbus-python's historical * behaviour. */ @@ -735,9 +594,6 @@ DBusPythonLong_tp_str(PyObject *self) { return (PyLong_Type.tp_repr)(self); } -#else -#define DBusPythonLong_tp_str 0 -#endif static void DBusPyLongBase_tp_dealloc(PyObject *self) @@ -791,58 +647,32 @@ PyObject *dbus_py_variant_level_const = NULL; PyObject *dbus_py_signature_const = NULL; PyObject *dbus_py__dbus_object_path__const = NULL; -#ifdef PY3 -#define INTERN (PyUnicode_InternFromString) -#else -/* Neither Python 2.6 nor 2.7 define the expected PyBytes_InternFromString - * alias in bytesobject.h. - */ -#define INTERN (PyString_InternFromString) -#endif - dbus_bool_t dbus_py_init_abstract(void) { _dbus_py_variant_levels = PyDict_New(); if (!_dbus_py_variant_levels) return 0; - dbus_py__dbus_object_path__const = INTERN("__dbus_object_path__"); + dbus_py__dbus_object_path__const = PyUnicode_InternFromString("__dbus_object_path__"); if (!dbus_py__dbus_object_path__const) return 0; - dbus_py_variant_level_const = INTERN("variant_level"); + dbus_py_variant_level_const = PyUnicode_InternFromString("variant_level"); if (!dbus_py_variant_level_const) return 0; - dbus_py_signature_const = INTERN("signature"); + dbus_py_signature_const = PyUnicode_InternFromString("signature"); if (!dbus_py_signature_const) return 0; -#ifdef PY3 DBusPyBytesBase_Type.tp_base = &PyBytes_Type; if (PyType_Ready(&DBusPyBytesBase_Type) < 0) return 0; -#else - DBusPyIntBase_Type.tp_base = &PyInt_Type; - if (PyType_Ready(&DBusPyIntBase_Type) < 0) return 0; - /* disable the tp_print copied from PyInt_Type, so tp_repr gets called as - desired */ - DBusPyIntBase_Type.tp_print = NULL; -#endif DBusPyFloatBase_Type.tp_base = &PyFloat_Type; if (PyType_Ready(&DBusPyFloatBase_Type) < 0) return 0; -#ifndef PY3 - DBusPyFloatBase_Type.tp_print = NULL; -#endif DBusPyLongBase_Type.tp_base = &PyLong_Type; if (PyType_Ready(&DBusPyLongBase_Type) < 0) return 0; -#ifndef PY3 - DBusPyLongBase_Type.tp_print = NULL; -#endif - DBusPyStrBase_Type.tp_base = &NATIVESTR_TYPE; + DBusPyStrBase_Type.tp_base = &PyUnicode_Type; if (PyType_Ready(&DBusPyStrBase_Type) < 0) return 0; -#ifndef PY3 - DBusPyStrBase_Type.tp_print = NULL; -#endif return 1; } @@ -851,15 +681,9 @@ dbus_bool_t dbus_py_insert_abstract_types(PyObject *this_module) { /* PyModule_AddObject steals a ref */ -#ifdef PY3 Py_INCREF(&DBusPyBytesBase_Type); if (PyModule_AddObject(this_module, "_BytesBase", (PyObject *)&DBusPyBytesBase_Type) < 0) return 0; -#else - Py_INCREF(&DBusPyIntBase_Type); - if (PyModule_AddObject(this_module, "_IntBase", - (PyObject *)&DBusPyIntBase_Type) < 0) return 0; -#endif Py_INCREF(&DBusPyLongBase_Type); Py_INCREF(&DBusPyStrBase_Type); Py_INCREF(&DBusPyFloatBase_Type); diff --git a/dbus_bindings/bus.c b/dbus_bindings/bus.c index 2c79cc0..ab1d4eb 100644 --- a/dbus_bindings/bus.c +++ b/dbus_bindings/bus.c @@ -45,13 +45,7 @@ DBusPyConnection_NewForBus(PyTypeObject *cls, PyObject *args, PyObject *kwargs) dbus_error_init(&error); - if (first && -#ifdef PY3 - PyUnicode_Check(first) -#else - PyBytes_Check(first) -#endif - ) + if (first && PyUnicode_Check(first)) { dbus_bool_t ret; @@ -72,7 +66,7 @@ DBusPyConnection_NewForBus(PyTypeObject *cls, PyObject *args, PyObject *kwargs) return (PyObject *)self; } - else if (!first || INTORLONG_CHECK(first)) + else if (!first || PyLong_Check(first)) { long type; PyObject *libdbusconn; @@ -156,7 +150,7 @@ DBusPyConnection_GetUniqueName(Connection *self, PyObject *args UNUSED) return DBusPyException_SetString("This connection has no unique name " "yet"); } - return NATIVESTR_FROMSTR(name); + return PyUnicode_FromString(name); } PyObject * diff --git a/dbus_bindings/bytes.c b/dbus_bindings/bytes.c index 611d239..1d5f652 100644 --- a/dbus_bindings/bytes.c +++ b/dbus_bindings/bytes.c @@ -32,12 +32,6 @@ #include "types-internal.h" -#ifdef PY3 -#define DBUS_PY_BYTE_BASE (DBusPyLongBase_Type) -#else -#define DBUS_PY_BYTE_BASE (DBusPyIntBase_Type) -#endif - PyDoc_STRVAR(Byte_tp_doc, "dbus.Byte(integer or bytes of length 1[, variant_level])\n" "\n" @@ -93,11 +87,11 @@ Byte_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs) if (PyBytes_GET_SIZE(obj) != 1) { goto bad_arg; } - obj = NATIVEINT_FROMLONG((unsigned char)(PyBytes_AS_STRING(obj)[0])); + obj = PyLong_FromLong((unsigned char)(PyBytes_AS_STRING(obj)[0])); if (!obj) goto bad_arg; } - else if (INTORLONG_CHECK(obj)) { + else if (PyLong_Check(obj)) { /* on Python 2 this accepts either int or long */ long i = PyLong_AsLong(obj); long my_variant_level; @@ -105,13 +99,9 @@ Byte_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs) if (i == -1 && PyErr_Occurred()) goto bad_arg; -#ifdef PY3 my_variant_level = dbus_py_variant_level_get(obj); if (my_variant_level < 0) return NULL; -#else - my_variant_level = ((DBusPyIntBase *)obj)->variant_level; -#endif if (Py_TYPE(obj) == cls && my_variant_level == variantness) { Py_INCREF(obj); return obj; @@ -128,7 +118,7 @@ Byte_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs) tuple = Py_BuildValue("(N)", obj); if (!tuple) return NULL; - obj = DBUS_PY_BYTE_BASE.tp_new(cls, tuple, kwargs); + obj = DBusPyLongBase_Type.tp_new(cls, tuple, kwargs); Py_CLEAR(tuple); return obj; @@ -144,7 +134,7 @@ bad_range: static PyObject * Byte_tp_str(PyObject *self) { - long i = NATIVEINT_ASLONG(self); + long i = PyLong_AsLong(self); unsigned char str[2] = { 0, 0 }; if (i == -1 && PyErr_Occurred()) @@ -189,7 +179,7 @@ PyTypeObject DBusPyByte_Type = { 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ - DEFERRED_ADDRESS(&DBUS_PY_BYTE_BASE), /* tp_base */ + DEFERRED_ADDRESS(&DBusPyLongBase_Type), /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ @@ -199,12 +189,6 @@ PyTypeObject DBusPyByte_Type = { Byte_new, /* tp_new */ }; -#ifdef PY3 -#define DBUS_PY_BYTEARRAY_BASE (DBusPyBytesBase_Type) -#else -#define DBUS_PY_BYTEARRAY_BASE (DBusPyStrBase_Type) -#endif - PyDoc_STRVAR(ByteArray_tp_doc, "ByteArray(str)\n" "\n" @@ -265,7 +249,7 @@ PyTypeObject DBusPyByteArray_Type = { 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ - DEFERRED_ADDRESS(&DBUS_PY_BYTEARRAY_BASE), /* tp_base */ + DEFERRED_ADDRESS(&DBusPyBytesBase_Type), /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ @@ -278,17 +262,11 @@ PyTypeObject DBusPyByteArray_Type = { dbus_bool_t dbus_py_init_byte_types(void) { - DBusPyByte_Type.tp_base = &DBUS_PY_BYTE_BASE; + DBusPyByte_Type.tp_base = &DBusPyLongBase_Type; if (PyType_Ready(&DBusPyByte_Type) < 0) return 0; -#ifndef PY3 - DBusPyByte_Type.tp_print = NULL; -#endif - DBusPyByteArray_Type.tp_base = &DBUS_PY_BYTEARRAY_BASE; + DBusPyByteArray_Type.tp_base = &DBusPyBytesBase_Type; if (PyType_Ready(&DBusPyByteArray_Type) < 0) return 0; -#ifndef PY3 - DBusPyByteArray_Type.tp_print = NULL; -#endif return 1; } diff --git a/dbus_bindings/conn-methods.c b/dbus_bindings/conn-methods.c index 62bdf86..f6ffc5b 100644 --- a/dbus_bindings/conn-methods.c +++ b/dbus_bindings/conn-methods.c @@ -567,7 +567,7 @@ Connection_get_unix_fd (Connection *self, PyObject *unused UNUSED) ok = dbus_connection_get_unix_fd (self->conn, &fd); Py_END_ALLOW_THREADS if (!ok) Py_RETURN_NONE; - return NATIVEINT_FROMLONG(fd); + return PyLong_FromLong(fd); } PyDoc_STRVAR(Connection_get_peer_unix_user__doc__, @@ -979,7 +979,7 @@ Connection_list_exported_child_objects (Connection *self, PyObject *args, return NULL; } for (kid_ptr = kids; *kid_ptr; kid_ptr++) { - PyObject *tmp = NATIVESTR_FROMSTR(*kid_ptr); + PyObject *tmp = PyUnicode_FromString(*kid_ptr); if (!tmp) { Py_CLEAR(ret); diff --git a/dbus_bindings/conn.c b/dbus_bindings/conn.c index 01c326b..59c3b36 100644 --- a/dbus_bindings/conn.c +++ b/dbus_bindings/conn.c @@ -450,11 +450,7 @@ PyTypeObject DBusPyConnection_Type = { 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ -#ifdef PY3 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, -#else - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS | Py_TPFLAGS_BASETYPE, -#endif Connection_tp_doc, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ diff --git a/dbus_bindings/containers.c b/dbus_bindings/containers.c index 7994d1f..1477752 100644 --- a/dbus_bindings/containers.c +++ b/dbus_bindings/containers.c @@ -165,27 +165,16 @@ Array_tp_init (DBusPyArray *self, PyObject *args, PyObject *kwargs) const char *c_str; PyObject *signature_as_bytes; - if ( -#ifdef PY3 - !PyUnicode_Check(signature) -#else - !PyBytes_Check(signature) -#endif - ) + if (!PyUnicode_Check(signature)) { PyErr_SetString(PyExc_TypeError, "str expected"); Py_CLEAR(signature); return -1; } -#ifdef PY3 if (!(signature_as_bytes = PyUnicode_AsUTF8String(signature))) { Py_CLEAR(signature); return -1; } -#else - signature_as_bytes = signature; - Py_INCREF(signature_as_bytes); -#endif c_str = PyBytes_AS_STRING(signature_as_bytes); @@ -394,20 +383,15 @@ Dict_tp_init(DBusPyDict *self, PyObject *args, PyObject *kwargs) const char *c_str; PyObject *signature_as_bytes; - if (!NATIVESTR_CHECK(signature)) { + if (!PyUnicode_Check(signature)) { PyErr_SetString(PyExc_TypeError, "str expected"); Py_CLEAR(signature); return -1; } -#ifdef PY3 if (!(signature_as_bytes = PyUnicode_AsUTF8String(signature))) { Py_CLEAR(signature); return -1; } -#else - signature_as_bytes = signature; - Py_INCREF(signature_as_bytes); -#endif c_str = PyBytes_AS_STRING(signature_as_bytes); switch (c_str[0]) { @@ -687,31 +671,8 @@ Struct_tp_getattro(PyObject *obj, PyObject *name) { PyObject *key, *value; -#ifdef PY3 if (PyUnicode_CompareWithASCIIString(name, "signature")) return dbus_py_variant_level_getattro(obj, name); -#else - if (PyBytes_Check(name)) { - Py_INCREF(name); - } - else if (PyUnicode_Check(name)) { - name = PyUnicode_AsEncodedString(name, NULL, NULL); - if (!name) { - return NULL; - } - } - else { - PyErr_SetString(PyExc_TypeError, "attribute name must be string"); - return NULL; - } - - if (strcmp(PyBytes_AS_STRING(name), "signature")) { - value = dbus_py_variant_level_getattro(obj, name); - Py_CLEAR(name); - return value; - } - Py_CLEAR(name); -#endif /* PY3 */ key = PyLong_FromVoidPtr(obj); @@ -777,21 +738,12 @@ dbus_py_init_container_types(void) DBusPyArray_Type.tp_base = &PyList_Type; if (PyType_Ready(&DBusPyArray_Type) < 0) return 0; -#ifndef PY3 - DBusPyArray_Type.tp_print = NULL; -#endif DBusPyDict_Type.tp_base = &PyDict_Type; if (PyType_Ready(&DBusPyDict_Type) < 0) return 0; -#ifndef PY3 - DBusPyDict_Type.tp_print = NULL; -#endif DBusPyStruct_Type.tp_base = &PyTuple_Type; if (PyType_Ready(&DBusPyStruct_Type) < 0) return 0; -#ifndef PY3 - DBusPyStruct_Type.tp_print = NULL; -#endif return 1; } diff --git a/dbus_bindings/dbus_bindings-internal.h b/dbus_bindings/dbus_bindings-internal.h index 7b1ca1e..eb48897 100644 --- a/dbus_bindings/dbus_bindings-internal.h +++ b/dbus_bindings/dbus_bindings-internal.h @@ -92,29 +92,7 @@ static inline int type##_CheckExact (PyObject *o) \ (PyUnicode_Check(obj) ? (obj) : NULL), \ (PyUnicode_Check(obj) ? NULL : PyBytes_AS_STRING(obj)) -#ifdef PY3 -#define NATIVEINT_TYPE (PyLong_Type) -#define NATIVEINT_FROMLONG(x) (PyLong_FromLong(x)) -#define NATIVEINT_ASLONG(x) (PyLong_AsLong(x)) -#define INTORLONG_CHECK(obj) (PyLong_Check(obj)) -#define NATIVESTR_TYPE (PyUnicode_Type) -#define NATIVESTR_CHECK(obj) (PyUnicode_Check(obj)) -#define NATIVESTR_FROMSTR(obj) (PyUnicode_FromString(obj)) -#else -#define NATIVEINT_TYPE (PyInt_Type) -#define NATIVEINT_FROMLONG(x) (PyInt_FromLong(x)) -#define NATIVEINT_ASLONG(x) (PyInt_AsLong(x)) -#define INTORLONG_CHECK(obj) (PyLong_Check(obj) || PyInt_Check(obj)) -#define NATIVESTR_TYPE (PyBytes_Type) -#define NATIVESTR_CHECK(obj) (PyBytes_Check(obj)) -#define NATIVESTR_FROMSTR(obj) (PyBytes_FromString(obj)) -#endif - -#ifdef PY3 PyMODINIT_FUNC PyInit__dbus_bindings(void); -#else -PyMODINIT_FUNC init_dbus_bindings(void); -#endif /* conn.c */ extern PyTypeObject DBusPyConnection_Type; @@ -154,10 +132,6 @@ DEFINE_CHECK(DBusPyByteArray) DEFINE_CHECK(DBusPyByte) extern PyTypeObject DBusPyString_Type; DEFINE_CHECK(DBusPyString) -#ifndef PY3 -extern PyTypeObject DBusPyUTF8String_Type; -DEFINE_CHECK(DBusPyUTF8String) -#endif extern PyTypeObject DBusPyDouble_Type; DEFINE_CHECK(DBusPyDouble) extern PyTypeObject DBusPyInt16_Type, DBusPyUInt16_Type; diff --git a/dbus_bindings/exceptions.c b/dbus_bindings/exceptions.c index 508537a..2940c2b 100644 --- a/dbus_bindings/exceptions.c +++ b/dbus_bindings/exceptions.c @@ -39,7 +39,7 @@ import_exception(void) return TRUE; } - name = NATIVESTR_FROMSTR("dbus.exceptions"); + name = PyUnicode_FromString("dbus.exceptions"); if (name == NULL) { return FALSE; } @@ -83,7 +83,7 @@ DBusPyException_ConsumeError(DBusError *error) } if (error->name) { - PyObject *name = NATIVESTR_FROMSTR(error->name); + PyObject *name = PyUnicode_FromString(error->name); int ret; if (!name) diff --git a/dbus_bindings/float.c b/dbus_bindings/float.c index eeabd5b..3ec1c13 100644 --- a/dbus_bindings/float.c +++ b/dbus_bindings/float.c @@ -130,16 +130,10 @@ dbus_py_init_float_types(void) { DBusPyDouble_Type.tp_base = &DBusPyFloatBase_Type; if (PyType_Ready(&DBusPyDouble_Type) < 0) return 0; -#ifndef PY3 - DBusPyDouble_Type.tp_print = NULL; -#endif #ifdef WITH_DBUS_FLOAT32 DBusPyFloat_Type.tp_base = &DBusPyFloatBase_Type; if (PyType_Ready(&DBusPyFloat_Type) < 0) return 0; -#ifndef PY3 - DBusPyFloat_Type.tp_print = NULL; -#endif #endif return 1; diff --git a/dbus_bindings/int.c b/dbus_bindings/int.c index 5944314..47d8404 100644 --- a/dbus_bindings/int.c +++ b/dbus_bindings/int.c @@ -29,14 +29,6 @@ #include "types-internal.h" -#ifdef PY3 -#define INTBASE (DBusPyLongBase_Type) -#define LONG_TYPE_NAME "int" -#else -#define INTBASE (DBusPyIntBase_Type) -#define LONG_TYPE_NAME "long" -#endif - /* Specific types =================================================== */ /* Boolean, a subclass of DBusPythonInt ============================= */ @@ -75,7 +67,7 @@ Boolean_tp_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs) } tuple = Py_BuildValue("(i)", PyObject_IsTrue(value) ? 1 : 0); if (!tuple) return NULL; - self = (INTBASE.tp_new)(cls, tuple, kwargs); + self = (DBusPyLongBase_Type.tp_new)(cls, tuple, kwargs); Py_CLEAR(tuple); return self; } @@ -90,13 +82,9 @@ static PyObject * Boolean_tp_repr(PyObject *self) { int is_true = PyObject_IsTrue(self); -#ifdef PY3 long variant_level = dbus_py_variant_level_get(self); if (variant_level < 0) return NULL; -#else - long variant_level = ((DBusPyIntBase *)self)->variant_level; -#endif if (is_true == -1) return NULL; @@ -143,7 +131,7 @@ PyTypeObject DBusPyBoolean_Type = { 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ - DEFERRED_ADDRESS(&INTBASE), /* tp_base */ + DEFERRED_ADDRESS(&DBusPyLongBase_Type), /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ @@ -192,7 +180,7 @@ dbus_py_int16_range_check(PyObject *obj) static PyObject * Int16_tp_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs) { - PyObject *self = (INTBASE.tp_new)(cls, args, kwargs); + PyObject *self = (DBusPyLongBase_Type.tp_new)(cls, args, kwargs); if (self && dbus_py_int16_range_check(self) == -1 && PyErr_Occurred()) { Py_CLEAR(self); return NULL; @@ -231,7 +219,7 @@ PyTypeObject DBusPyInt16_Type = { 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ - DEFERRED_ADDRESS(&INTBASE), /* tp_base */ + DEFERRED_ADDRESS(&DBusPyLongBase_Type), /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ @@ -280,7 +268,7 @@ dbus_py_uint16_range_check(PyObject *obj) static PyObject * UInt16_tp_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs) { - PyObject *self = (INTBASE.tp_new)(cls, args, kwargs); + PyObject *self = (DBusPyLongBase_Type.tp_new)(cls, args, kwargs); if (self && dbus_py_uint16_range_check(self) == (dbus_uint16_t)(-1) && PyErr_Occurred()) { @@ -321,7 +309,7 @@ PyTypeObject DBusPyUInt16_Type = { 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ - DEFERRED_ADDRESS(&INTBASE), /* tp_base */ + DEFERRED_ADDRESS(&DBusPyLongBase_Type), /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ @@ -370,7 +358,7 @@ dbus_py_int32_range_check(PyObject *obj) static PyObject * Int32_tp_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs) { - PyObject *self = (INTBASE.tp_new)(cls, args, kwargs); + PyObject *self = (DBusPyLongBase_Type.tp_new)(cls, args, kwargs); if (self && dbus_py_int32_range_check(self) == -1 && PyErr_Occurred()) { Py_CLEAR(self); return NULL; @@ -409,7 +397,7 @@ PyTypeObject DBusPyInt32_Type = { 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ - DEFERRED_ADDRESS(&INTBASE), /* tp_base */ + DEFERRED_ADDRESS(&DBusPyLongBase_Type), /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ @@ -422,7 +410,7 @@ PyTypeObject DBusPyInt32_Type = { /* UInt32 =========================================================== */ PyDoc_STRVAR(UInt32_tp_doc, -"dbus.UInt32(value: " LONG_TYPE_NAME "[, variant_level: int])\n" +"dbus.UInt32(value: int[, variant_level: int])\n" "\n" "An unsigned 32-bit integer between 0 and 0xFFFF FFFF, represented as a\n" "subtype of ``long`` in Python 2 or ``int`` in Python 3.\n" @@ -505,7 +493,7 @@ PyTypeObject DBusPyUInt32_Type = { 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ - DEFERRED_ADDRESS(&DBusPyLongBase_Type), /* tp_base */ + DEFERRED_ADDRESS(&DBusPyLongBase_Type), /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ @@ -518,7 +506,7 @@ PyTypeObject DBusPyUInt32_Type = { /* Int64 =========================================================== */ PyDoc_STRVAR(Int64_tp_doc, -"dbus.Int64(value: " LONG_TYPE_NAME "[, variant_level: int])\n" +"dbus.Int64(value: int[, variant_level: int])\n" "\n" "A signed 64-bit integer between -0x8000 0000 0000 0000 and\n" "+0x7FFF FFFF FFFF FFFF, represented as a\n" @@ -611,7 +599,7 @@ PyTypeObject DBusPyInt64_Type = { 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ - DEFERRED_ADDRESS(&DBusPyLongBase_Type), /* tp_base */ + DEFERRED_ADDRESS(&DBusPyLongBase_Type), /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ @@ -624,7 +612,7 @@ PyTypeObject DBusPyInt64_Type = { /* UInt64 =========================================================== */ PyDoc_STRVAR(UInt64_tp_doc, -"dbus.UInt64(value: " LONG_TYPE_NAME "[, variant_level: int])\n" +"dbus.UInt64(value: int[, variant_level: int])\n" "\n" "An unsigned 64-bit integer between 0 and 0xFFFF FFFF FFFF FFFF,\n" "subtype of ``long`` in Python 2 or ``int`` in Python 3.\n" @@ -712,7 +700,7 @@ PyTypeObject DBusPyUInt64_Type = { 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ - DEFERRED_ADDRESS(&DBusPyLongBase_Type), /* tp_base */ + DEFERRED_ADDRESS(&DBusPyLongBase_Type), /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ @@ -725,51 +713,28 @@ PyTypeObject DBusPyUInt64_Type = { dbus_bool_t dbus_py_init_int_types(void) { - DBusPyInt16_Type.tp_base = &INTBASE; + DBusPyInt16_Type.tp_base = &DBusPyLongBase_Type; if (PyType_Ready(&DBusPyInt16_Type) < 0) return 0; -#ifndef PY3 - /* disable the tp_print copied from PyInt_Type, so tp_repr gets called as - desired */ - DBusPyInt16_Type.tp_print = NULL; -#endif - DBusPyUInt16_Type.tp_base = &INTBASE; + DBusPyUInt16_Type.tp_base = &DBusPyLongBase_Type; if (PyType_Ready(&DBusPyUInt16_Type) < 0) return 0; -#ifndef PY3 - DBusPyUInt16_Type.tp_print = NULL; -#endif - DBusPyInt32_Type.tp_base = &INTBASE; + DBusPyInt32_Type.tp_base = &DBusPyLongBase_Type; if (PyType_Ready(&DBusPyInt32_Type) < 0) return 0; -#ifndef PY3 - DBusPyInt32_Type.tp_print = NULL; -#endif DBusPyUInt32_Type.tp_base = &DBusPyLongBase_Type; if (PyType_Ready(&DBusPyUInt32_Type) < 0) return 0; -#ifndef PY3 - DBusPyUInt32_Type.tp_print = NULL; -#endif #if defined(DBUS_HAVE_INT64) && defined(HAVE_LONG_LONG) DBusPyInt64_Type.tp_base = &DBusPyLongBase_Type; if (PyType_Ready(&DBusPyInt64_Type) < 0) return 0; -#ifndef PY3 - DBusPyInt64_Type.tp_print = NULL; -#endif DBusPyUInt64_Type.tp_base = &DBusPyLongBase_Type; if (PyType_Ready(&DBusPyUInt64_Type) < 0) return 0; -#ifndef PY3 - DBusPyUInt64_Type.tp_print = NULL; -#endif #endif - DBusPyBoolean_Type.tp_base = &INTBASE; + DBusPyBoolean_Type.tp_base = &DBusPyLongBase_Type; if (PyType_Ready(&DBusPyBoolean_Type) < 0) return 0; -#ifndef PY3 - DBusPyBoolean_Type.tp_print = NULL; -#endif return 1; } diff --git a/dbus_bindings/message-append.c b/dbus_bindings/message-append.c index 3257405..9c6b5f7 100644 --- a/dbus_bindings/message-append.c +++ b/dbus_bindings/message-append.c @@ -44,11 +44,6 @@ get_variant_level(PyObject *obj) if (DBusPyString_Check(obj)) { return ((DBusPyString *)obj)->variant_level; } -#ifndef PY3 - else if (DBusPyIntBase_Check(obj)) { - return ((DBusPyIntBase *)obj)->variant_level; - } -#endif else if (DBusPyFloatBase_Check(obj)) { return ((DBusPyFloatBase *)obj)->variant_level; } @@ -59,9 +54,7 @@ get_variant_level(PyObject *obj) return ((DBusPyDict *)obj)->variant_level; } else if (DBusPyLongBase_Check(obj) || -#ifdef PY3 DBusPyBytesBase_Check(obj) || -#endif DBusPyStrBase_Check(obj) || DBusPyStruct_Check(obj)) { return dbus_py_variant_level_get(obj); @@ -188,11 +181,11 @@ _signature_string_from_pyobject(PyObject *obj, long *variant_level_ptr) *variant_level_ptr = variant_level; } else if (variant_level > 0) { - return NATIVESTR_FROMSTR(DBUS_TYPE_VARIANT_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_VARIANT_AS_STRING); } if (obj == Py_True || obj == Py_False) { - return NATIVESTR_FROMSTR(DBUS_TYPE_BOOLEAN_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_BOOLEAN_AS_STRING); } magic_attr = get_object_path(obj); @@ -200,94 +193,67 @@ _signature_string_from_pyobject(PyObject *obj, long *variant_level_ptr) return NULL; if (magic_attr != Py_None) { Py_CLEAR(magic_attr); - return NATIVESTR_FROMSTR(DBUS_TYPE_OBJECT_PATH_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_OBJECT_PATH_AS_STRING); } Py_CLEAR(magic_attr); /* Ordering is important: some of these are subclasses of each other. */ -#ifdef PY3 if (PyLong_Check(obj)) { if (DBusPyUInt64_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_UINT64_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_UINT64_AS_STRING); else if (DBusPyInt64_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_INT64_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_INT64_AS_STRING); else if (DBusPyUInt32_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_UINT32_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_UINT32_AS_STRING); else if (DBusPyInt32_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_INT32_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_INT32_AS_STRING); else if (DBusPyUInt16_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_UINT16_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_UINT16_AS_STRING); else if (DBusPyInt16_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_INT16_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_INT16_AS_STRING); else if (DBusPyByte_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_BYTE_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_BYTE_AS_STRING); else if (DBusPyBoolean_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_BOOLEAN_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_BOOLEAN_AS_STRING); else - return NATIVESTR_FROMSTR(DBUS_TYPE_INT32_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_INT32_AS_STRING); } -#else /* !PY3 */ - if (PyInt_Check(obj)) { - if (DBusPyInt16_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_INT16_AS_STRING); - else if (DBusPyInt32_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_INT32_AS_STRING); - else if (DBusPyByte_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_BYTE_AS_STRING); - else if (DBusPyUInt16_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_UINT16_AS_STRING); - else if (DBusPyBoolean_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_BOOLEAN_AS_STRING); - else - return NATIVESTR_FROMSTR(DBUS_TYPE_INT32_AS_STRING); - } - else if (PyLong_Check(obj)) { - if (DBusPyInt64_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_INT64_AS_STRING); - else if (DBusPyUInt32_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_UINT32_AS_STRING); - else if (DBusPyUInt64_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_UINT64_AS_STRING); - else - return NATIVESTR_FROMSTR(DBUS_TYPE_INT64_AS_STRING); - } -#endif /* PY3 */ else if (PyUnicode_Check(obj)) { /* Object paths and signatures are unicode subtypes in Python 3 * (the first two cases will never be true in Python 2) */ if (DBusPyObjectPath_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_OBJECT_PATH_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_OBJECT_PATH_AS_STRING); else if (DBusPySignature_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_SIGNATURE_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_SIGNATURE_AS_STRING); else - return NATIVESTR_FROMSTR(DBUS_TYPE_STRING_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_STRING_AS_STRING); } #if defined(DBUS_TYPE_UNIX_FD) else if (DBusPyUnixFd_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_UNIX_FD_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_UNIX_FD_AS_STRING); #endif else if (PyFloat_Check(obj)) { #ifdef WITH_DBUS_FLOAT32 if (DBusPyDouble_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_DOUBLE_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_DOUBLE_AS_STRING); else if (DBusPyFloat_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_FLOAT_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_FLOAT_AS_STRING); else #endif - return NATIVESTR_FROMSTR(DBUS_TYPE_DOUBLE_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_DOUBLE_AS_STRING); } else if (PyBytes_Check(obj)) { /* Object paths and signatures are bytes subtypes in Python 2 * (the first two cases will never be true in Python 3) */ if (DBusPyObjectPath_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_OBJECT_PATH_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_OBJECT_PATH_AS_STRING); else if (DBusPySignature_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_SIGNATURE_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_SIGNATURE_AS_STRING); else if (DBusPyByteArray_Check(obj)) - return NATIVESTR_FROMSTR(DBUS_TYPE_ARRAY_AS_STRING + return PyUnicode_FromString(DBUS_TYPE_ARRAY_AS_STRING DBUS_TYPE_BYTE_AS_STRING); else - return NATIVESTR_FROMSTR(DBUS_TYPE_STRING_AS_STRING); + return PyUnicode_FromString(DBUS_TYPE_STRING_AS_STRING); } else if (PyTuple_Check(obj)) { Py_ssize_t len = PyTuple_GET_SIZE(obj); @@ -304,12 +270,12 @@ _signature_string_from_pyobject(PyObject *obj, long *variant_level_ptr) return NULL; } /* Set the first and last elements of list to be the parentheses */ - item = NATIVESTR_FROMSTR(DBUS_STRUCT_BEGIN_CHAR_AS_STRING); + item = PyUnicode_FromString(DBUS_STRUCT_BEGIN_CHAR_AS_STRING); if (PyList_SetItem(list, 0, item) < 0) { Py_CLEAR(list); return NULL; } - item = NATIVESTR_FROMSTR(DBUS_STRUCT_END_CHAR_AS_STRING); + item = PyUnicode_FromString(DBUS_STRUCT_END_CHAR_AS_STRING); if (PyList_SetItem(list, len + 1, item) < 0) { Py_CLEAR(list); return NULL; @@ -337,7 +303,7 @@ _signature_string_from_pyobject(PyObject *obj, long *variant_level_ptr) } item = NULL; } - empty_str = NATIVESTR_FROMSTR(""); + empty_str = PyUnicode_FromString(""); if (!empty_str) { /* really shouldn't happen */ Py_CLEAR(list); @@ -351,9 +317,8 @@ _signature_string_from_pyobject(PyObject *obj, long *variant_level_ptr) } else if (PyList_Check(obj)) { PyObject *tmp; - PyObject *ret = NATIVESTR_FROMSTR(DBUS_TYPE_ARRAY_AS_STRING); + PyObject *ret = PyUnicode_FromString(DBUS_TYPE_ARRAY_AS_STRING); if (!ret) return NULL; -#ifdef PY3 if (DBusPyArray_Check(obj) && PyUnicode_Check(((DBusPyArray *)obj)->signature)) { @@ -362,14 +327,6 @@ _signature_string_from_pyobject(PyObject *obj, long *variant_level_ptr) Py_CLEAR(ret); return concat; } -#else - if (DBusPyArray_Check(obj) && - PyBytes_Check(((DBusPyArray *)obj)->signature)) - { - PyBytes_Concat(&ret, ((DBusPyArray *)obj)->signature); - return ret; - } -#endif if (PyList_GET_SIZE(obj) == 0) { /* No items, so fail. Or should we guess "av"? */ PyErr_SetString(PyExc_ValueError, "Unable to guess signature " @@ -379,24 +336,18 @@ _signature_string_from_pyobject(PyObject *obj, long *variant_level_ptr) tmp = PyList_GetItem(obj, 0); tmp = _signature_string_from_pyobject(tmp, NULL); if (!tmp) return NULL; -#ifdef PY3 { PyObject *concat = PyUnicode_Concat(ret, tmp); Py_CLEAR(ret); Py_CLEAR(tmp); return concat; } -#else - PyBytes_ConcatAndDel(&ret, tmp); - return ret; -#endif } else if (PyDict_Check(obj)) { PyObject *key, *value, *keysig, *valuesig; Py_ssize_t pos = 0; PyObject *ret = NULL; -#ifdef PY3 if (DBusPyDict_Check(obj) && PyUnicode_Check(((DBusPyDict *)obj)->signature)) { @@ -406,19 +357,6 @@ _signature_string_from_pyobject(PyObject *obj, long *variant_level_ptr) DBUS_DICT_ENTRY_END_CHAR_AS_STRING), ((DBusPyDict *)obj)->signature); } -#else - if (DBusPyDict_Check(obj) && - PyBytes_Check(((DBusPyDict *)obj)->signature)) - { - const char *sig = PyBytes_AS_STRING(((DBusPyDict *)obj)->signature); - - return PyBytes_FromFormat((DBUS_TYPE_ARRAY_AS_STRING - DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING - "%s" - DBUS_DICT_ENTRY_END_CHAR_AS_STRING), - sig); - } -#endif if (!PyDict_Next(obj, &pos, &key, &value)) { /* No items, so fail. Or should we guess "a{vv}"? */ PyErr_SetString(PyExc_ValueError, "Unable to guess signature " @@ -428,20 +366,11 @@ _signature_string_from_pyobject(PyObject *obj, long *variant_level_ptr) keysig = _signature_string_from_pyobject(key, NULL); valuesig = _signature_string_from_pyobject(value, NULL); if (keysig && valuesig) { -#ifdef PY3 ret = PyUnicode_FromFormat((DBUS_TYPE_ARRAY_AS_STRING DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING "%U%U" DBUS_DICT_ENTRY_END_CHAR_AS_STRING), keysig, valuesig); -#else - ret = PyBytes_FromFormat((DBUS_TYPE_ARRAY_AS_STRING - DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING - "%s%s" - DBUS_DICT_ENTRY_END_CHAR_AS_STRING), - PyBytes_AS_STRING(keysig), - PyBytes_AS_STRING(valuesig)); -#endif } Py_CLEAR(keysig); Py_CLEAR(valuesig); @@ -644,7 +573,7 @@ _message_iter_append_unixfd(DBusMessageIter *appender, PyObject *obj) int fd; long original_fd; - if (INTORLONG_CHECK(obj)) + if (PyLong_Check(obj)) { /* on Python 2 this accepts either int or long */ original_fd = PyLong_AsLong(obj); diff --git a/dbus_bindings/message-get-args.c b/dbus_bindings/message-get-args.c index c097160..6dad272 100644 --- a/dbus_bindings/message-get-args.c +++ b/dbus_bindings/message-get-args.c @@ -45,11 +45,6 @@ char dbus_py_Message_get_args_list__doc__[] = ( " it's off by default for consistency.\n" "\n" " If false (default), convert them into a dbus.Array of Bytes.\n" -#ifndef PY3 -" `utf8_strings` : bool\n" -" If true, return D-Bus strings as Python `bytes` objects (in UTF-8).\n" -" If false (default), return D-Bus strings as Python `unicode` objects.\n" -#endif "\n" "Most of the type mappings should be fairly obvious:\n" "\n" @@ -75,9 +70,6 @@ char dbus_py_Message_get_args_list__doc__[] = ( typedef struct { int byte_arrays; -#ifndef PY3 - int utf8_strings; -#endif } Message_get_args_options; static PyObject *_message_iter_get_pyobject(DBusMessageIter *iter, @@ -205,7 +197,7 @@ _message_iter_get_pyobject(DBusMessageIter *iter, if (variant_level > 0 && type != DBUS_TYPE_VARIANT) { PyObject *variant_level_int; - variant_level_int = NATIVEINT_FROMLONG(variant_level); + variant_level_int = PyLong_FromLong(variant_level); if (!variant_level_int) { return NULL; } @@ -232,28 +224,16 @@ _message_iter_get_pyobject(DBusMessageIter *iter, case DBUS_TYPE_STRING: DBG("%s", "found a string"); dbus_message_iter_get_basic(iter, &u.str); -#ifndef PY3 - if (opts->utf8_strings) { - args = Py_BuildValue("(s)", u.str); - if (!args) break; - ret = PyObject_Call((PyObject *)&DBusPyUTF8String_Type, - args, kwargs); + unicode = PyUnicode_DecodeUTF8(u.str, strlen(u.str), NULL); + if (!unicode) { + break; } - else { -#endif - unicode = PyUnicode_DecodeUTF8(u.str, strlen(u.str), NULL); - if (!unicode) { - break; - } - args = Py_BuildValue("(N)", unicode); - if (!args) { - break; - } - ret = PyObject_Call((PyObject *)&DBusPyString_Type, - args, kwargs); -#ifndef PY3 + args = Py_BuildValue("(N)", unicode); + if (!args) { + break; } -#endif + ret = PyObject_Call((PyObject *)&DBusPyString_Type, + args, kwargs); break; case DBUS_TYPE_SIGNATURE: @@ -410,11 +390,7 @@ _message_iter_get_pyobject(DBusMessageIter *iter, * for an empty byte-blob... */ u.str = ""; } -#ifdef PY3 args = Py_BuildValue("(y#)", u.str, (Py_ssize_t)n); -#else - args = Py_BuildValue("(s#)", u.str, (Py_ssize_t)n); -#endif if (!args) break; ret = PyObject_Call((PyObject *)&DBusPyByteArray_Type, args, kwargs); @@ -498,13 +474,8 @@ _message_iter_get_pyobject(DBusMessageIter *iter, PyObject * dbus_py_Message_get_args_list(Message *self, PyObject *args, PyObject *kwargs) { -#ifdef PY3 Message_get_args_options opts = { 0 }; static char *argnames[] = { "byte_arrays", NULL }; -#else - Message_get_args_options opts = { 0, 0 }; - static char *argnames[] = { "byte_arrays", "utf8_strings", NULL }; -#endif PyObject *list; DBusMessageIter iter; @@ -524,16 +495,9 @@ dbus_py_Message_get_args_list(Message *self, PyObject *args, PyObject *kwargs) "arguments"); return NULL; } -#ifdef PY3 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:get_args_list", argnames, &(opts.byte_arrays))) return NULL; -#else - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ii:get_args_list", - argnames, - &(opts.byte_arrays), - &(opts.utf8_strings))) return NULL; -#endif if (!self->msg) return DBusPy_RaiseUnusableMessage(); list = PyList_New(0); diff --git a/dbus_bindings/message.c b/dbus_bindings/message.c index 7c0c192..4ebd59b 100644 --- a/dbus_bindings/message.c +++ b/dbus_bindings/message.c @@ -392,7 +392,7 @@ static PyObject * Message_get_type(Message *self, PyObject *unused UNUSED) { if (!self->msg) return DBusPy_RaiseUnusableMessage(); - return NATIVEINT_FROMLONG(dbus_message_get_type(self->msg)); + return PyLong_FromLong(dbus_message_get_type(self->msg)); } PyDoc_STRVAR(Message_get_serial__doc__, @@ -466,7 +466,7 @@ Message_get_member(Message *self, PyObject *unused UNUSED) if (!c_str) { Py_RETURN_NONE; } - return NATIVESTR_FROMSTR(c_str); + return PyUnicode_FromString(c_str); } PyDoc_STRVAR(Message_has_member__doc__, @@ -541,7 +541,7 @@ Message_get_path_decomposed(Message *self, PyObject *unused UNUSED) Py_RETURN_NONE; } for (ptr = paths; *ptr; ptr++) { - PyObject *str = NATIVESTR_FROMSTR(*ptr); + PyObject *str = PyUnicode_FromString(*ptr); if (!str) { Py_CLEAR(ret); @@ -627,7 +627,7 @@ Message_get_sender(Message *self, PyObject *unused UNUSED) if (!c_str) { Py_RETURN_NONE; } - return NATIVESTR_FROMSTR(c_str); + return PyUnicode_FromString(c_str); } PyDoc_STRVAR(Message_has_sender__doc__, @@ -673,7 +673,7 @@ Message_get_destination(Message *self, PyObject *unused UNUSED) if (!c_str) { Py_RETURN_NONE; } - return NATIVESTR_FROMSTR(c_str); + return PyUnicode_FromString(c_str); } PyDoc_STRVAR(Message_has_destination__doc__, @@ -718,7 +718,7 @@ Message_get_interface(Message *self, PyObject *unused UNUSED) if (!c_str) { Py_RETURN_NONE; } - return NATIVESTR_FROMSTR(c_str); + return PyUnicode_FromString(c_str); } PyDoc_STRVAR(Message_has_interface__doc__, @@ -763,7 +763,7 @@ Message_get_error_name(Message *self, PyObject *unused UNUSED) if (!c_str) { Py_RETURN_NONE; } - return NATIVESTR_FROMSTR(c_str); + return PyUnicode_FromString(c_str); } PyDoc_STRVAR(Message_set_error_name__doc__, diff --git a/dbus_bindings/module.c b/dbus_bindings/module.c index 2779bfa..8ca99a5 100644 --- a/dbus_bindings/module.c +++ b/dbus_bindings/module.c @@ -235,17 +235,12 @@ static PyMethodDef module_functions[] = { }; PyMODINIT_FUNC -#ifdef PY3 PyInit__dbus_bindings(void) -#else -init_dbus_bindings(void) -#endif { PyObject *this_module = NULL, *c_api; static const int API_count = DBUS_BINDINGS_API_COUNT; static _dbus_py_func_ptr dbus_bindings_API[DBUS_BINDINGS_API_COUNT]; -#ifdef PY3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_dbus_bindings", /* m_name */ @@ -257,7 +252,6 @@ init_dbus_bindings(void) NULL, /* m_clear */ NULL /* m_free */ }; -#endif dbus_bindings_API[0] = (_dbus_py_func_ptr)&API_count; dbus_bindings_API[1] = (_dbus_py_func_ptr)DBusPyConnection_BorrowDBusConnection; @@ -281,12 +275,7 @@ init_dbus_bindings(void) if (!dbus_py_init_conn_types()) goto init_error; if (!dbus_py_init_server_types()) goto init_error; -#ifdef PY3 this_module = PyModule_Create(&moduledef); -#else - this_module = Py_InitModule3("_dbus_bindings", - module_functions, module_doc); -#endif if (!this_module) goto init_error; if (!dbus_py_insert_abstract_types(this_module)) goto init_error; @@ -409,26 +398,17 @@ init_dbus_bindings(void) if (PyModule_AddIntConstant(this_module, "_python_version", PY_VERSION_HEX) < 0) goto init_error; -#ifdef PY3 c_api = PyCapsule_New((void *)dbus_bindings_API, PYDBUS_CAPSULE_NAME, NULL); -#else - c_api = PyCObject_FromVoidPtr ((void *)dbus_bindings_API, NULL); -#endif if (!c_api) { goto init_error; } PyModule_AddObject(this_module, "_C_API", c_api); -#ifdef PY3 return this_module; init_error: Py_CLEAR(this_module); return NULL; -#else - init_error: - return; -#endif } /* vim:set ft=c cino< sw=4 sts=4 et: */ diff --git a/dbus_bindings/server.c b/dbus_bindings/server.c index dfbfa53..705ba2f 100644 --- a/dbus_bindings/server.c +++ b/dbus_bindings/server.c @@ -496,7 +496,7 @@ Server_get_address(Server *self, PyObject *args UNUSED) address = dbus_server_get_address(self->server); Py_END_ALLOW_THREADS - return NATIVESTR_FROMSTR(address); + return PyUnicode_FromString(address); } PyDoc_STRVAR(Server_get_id__doc__, @@ -513,7 +513,7 @@ Server_get_id(Server *self, PyObject *args UNUSED) id = dbus_server_get_id(self->server); Py_END_ALLOW_THREADS - return NATIVESTR_FROMSTR(id); + return PyUnicode_FromString(id); } PyDoc_STRVAR(Server_get_is_connected__doc__, @@ -565,11 +565,7 @@ PyTypeObject DBusPyServer_Type = { 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ -#ifdef PY3 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, -#else - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS | Py_TPFLAGS_BASETYPE, -#endif Server_tp_doc, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ diff --git a/dbus_bindings/signature.c b/dbus_bindings/signature.c index 403907d..cd2ba03 100644 --- a/dbus_bindings/signature.c +++ b/dbus_bindings/signature.c @@ -146,16 +146,11 @@ Signature_tp_iter(PyObject *self) if (!iter) return NULL; -#ifdef PY3 self_as_bytes = PyUnicode_AsUTF8String(self); if (!self_as_bytes) { Py_CLEAR(iter); return NULL; } -#else - self_as_bytes = self; - Py_INCREF(self_as_bytes); -#endif if (PyBytes_GET_SIZE(self_as_bytes) > 0) { iter->bytes = self_as_bytes; @@ -235,9 +230,6 @@ dbus_py_init_signature(void) DBusPySignature_Type.tp_base = &DBusPyStrBase_Type; if (PyType_Ready(&DBusPySignature_Type) < 0) return 0; -#ifndef PY3 - DBusPySignature_Type.tp_print = NULL; -#endif return 1; } diff --git a/dbus_bindings/string.c b/dbus_bindings/string.c index b6f42ac..e57a483 100644 --- a/dbus_bindings/string.c +++ b/dbus_bindings/string.c @@ -30,103 +30,6 @@ #include "types-internal.h" #include -#ifndef PY3 -/* UTF-8 string representation ====================================== */ - -PyDoc_STRVAR(UTF8String_tp_doc, -"dbus.UTF8String(value: bytes or unicode[, variant_level: int=0])\n" -"\n" -"A string represented using UTF-8 - a subtype of `bytes`.\n" -"This type is only available in Python 2.\n" -"\n" -"All strings on D-Bus are required to be valid Unicode; in the \"wire\n" -"protocol\" they're transported as UTF-8.\n" -"\n" -"By default, when byte arrays are converted from D-Bus to Python, they\n" -"come out as a `dbus.String`, which is a subtype of `unicode`.\n" -"If you prefer to get UTF-8 strings (as instances of this class) or you\n" -"want to avoid the conversion overhead of going from UTF-8 to Python's\n" -"internal Unicode representation, you can pass the ``utf8_strings=True``\n" -"keyword argument to any of these methods:\n" -"\n" -"* any D-Bus method proxy, or ``connect_to_signal``, on the objects returned\n" -" by `Bus.get_object`\n" -"* any D-Bus method on a `dbus.Interface`\n" -"* `dbus.Interface.connect_to_signal`\n" -"* `Bus.add_signal_receiver`\n" -"\n" -"If value is a bytes object it must be valid UTF-8.\n" -"\n" -"variant_level must be non-negative; the default is 0.\n" -"\n" -".. py:attribute:: variant_level\n" -"\n" -" Indicates how many nested Variant containers this object\n" -" is contained in: if a message's wire format has a variant containing a\n" -" variant containing a string, this is represented in Python by a\n" -" String or UTF8String with variant_level==2.\n" -"\n" -":Since: 0.80 (in older versions, use dbus.String)\n" -); - -static PyObject * -UTF8String_tp_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs) -{ - const char *str = NULL; - long variantness = 0; - static char *argnames[] = {"value", "variant_level", NULL}; - PyObject *unicode; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|l:__new__", argnames, - &str, &variantness)) return NULL; - unicode = PyUnicode_DecodeUTF8(str, strlen(str), NULL); - if (!unicode) return NULL; - Py_CLEAR(unicode); - return (DBusPyStrBase_Type.tp_new)(cls, args, kwargs); -} - -PyTypeObject DBusPyUTF8String_Type = { - PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) - "dbus.UTF8String", - 0, - 0, - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - UTF8String_tp_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - DEFERRED_ADDRESS(&DBusPyStrBase_Type), /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - UTF8String_tp_new, /* tp_new */ -}; -#endif /* !PY3 */ - /* Object path ====================================================== */ PyDoc_STRVAR(ObjectPath_tp_doc, @@ -339,21 +242,9 @@ dbus_py_init_string_types(void) } DBusPyString_Type.tp_base = &PyUnicode_Type; if (PyType_Ready(&DBusPyString_Type) < 0) return 0; -#ifndef PY3 - DBusPyString_Type.tp_print = NULL; -#endif - -#ifndef PY3 - DBusPyUTF8String_Type.tp_base = &DBusPyStrBase_Type; - if (PyType_Ready(&DBusPyUTF8String_Type) < 0) return 0; - DBusPyUTF8String_Type.tp_print = NULL; -#endif DBusPyObjectPath_Type.tp_base = &DBusPyStrBase_Type; if (PyType_Ready(&DBusPyObjectPath_Type) < 0) return 0; -#ifndef PY3 - DBusPyObjectPath_Type.tp_print = NULL; -#endif return 1; } @@ -369,11 +260,6 @@ dbus_py_insert_string_types(PyObject *this_module) if (PyModule_AddObject(this_module, "String", (PyObject *)&DBusPyString_Type) < 0) return 0; -#ifndef PY3 - Py_INCREF(&DBusPyUTF8String_Type); - if (PyModule_AddObject(this_module, "UTF8String", - (PyObject *)&DBusPyUTF8String_Type) < 0) return 0; -#endif return 1; } diff --git a/dbus_bindings/types-internal.h b/dbus_bindings/types-internal.h index 37879cf..02c931f 100644 --- a/dbus_bindings/types-internal.h +++ b/dbus_bindings/types-internal.h @@ -35,24 +35,9 @@ */ #include -/* In Python 2.x, we need this to define the type of PyLongObject */ -#ifndef PY3 -#include -#endif - #ifndef DBUS_BINDINGS_TYPES_INTERNAL_H #define DBUS_BINDINGS_TYPES_INTERNAL_H -#ifndef PY3 -extern PyTypeObject DBusPyIntBase_Type; -DEFINE_CHECK(DBusPyIntBase) - -typedef struct { - PyIntObject base; - long variant_level; -} DBusPyIntBase; -#endif - extern PyTypeObject DBusPyLongBase_Type; DEFINE_CHECK(DBusPyLongBase) @@ -72,10 +57,8 @@ typedef struct { extern PyTypeObject DBusPyStrBase_Type; DEFINE_CHECK(DBusPyStrBase) -#ifdef PY3 extern PyTypeObject DBusPyBytesBase_Type; DEFINE_CHECK(DBusPyBytesBase) -#endif dbus_int16_t dbus_py_int16_range_check(PyObject *); dbus_uint16_t dbus_py_uint16_range_check(PyObject *); diff --git a/dbus_bindings/unixfd.c b/dbus_bindings/unixfd.c index ed99386..63a2402 100644 --- a/dbus_bindings/unixfd.c +++ b/dbus_bindings/unixfd.c @@ -77,7 +77,7 @@ make_fd(PyObject *arg, int *fd) { long fd_arg; - if (INTORLONG_CHECK(arg)) + if (PyLong_Check(arg)) { /* on Python 2 this accepts either int or long */ fd_arg = PyLong_AsLong(arg); diff --git a/dbus_glib_bindings/module.c b/dbus_glib_bindings/module.c index 6614394..8b04eef 100644 --- a/dbus_glib_bindings/module.c +++ b/dbus_glib_bindings/module.c @@ -29,11 +29,7 @@ #include #include -#ifdef PY3 PyMODINIT_FUNC PyInit__dbus_glib_bindings(void); -#else -PyMODINIT_FUNC init_dbus_glib_bindings(void); -#endif #if defined(__GNUC__) # if __GNUC__ >= 3 @@ -175,7 +171,6 @@ static PyMethodDef module_functions[] = { {NULL, NULL, 0, NULL} }; -#ifdef PY3 PyMODINIT_FUNC PyInit__dbus_glib_bindings(void) { @@ -201,17 +196,5 @@ PyInit__dbus_glib_bindings(void) } return this_module; } -#else -PyMODINIT_FUNC -init_dbus_glib_bindings(void) -{ - PyObject *this_module; - - if (import_dbus_bindings("_dbus_glib_bindings") < 0) return; - this_module = Py_InitModule3 ("_dbus_glib_bindings", module_functions, - module_doc); - if (!this_module) return; -} -#endif /* vim:set ft=c cino< sw=4 sts=4 et: */ diff --git a/include/dbus/dbus-python.h b/include/dbus/dbus-python.h index b67e7c4..72a9bf1 100644 --- a/include/dbus/dbus-python.h +++ b/include/dbus/dbus-python.h @@ -34,10 +34,7 @@ #include #include -#if PY_MAJOR_VERSION >= 3 -#define PY3 #define PYDBUS_CAPSULE_NAME "_dbus_bindings._C_API" -#endif DBUS_BEGIN_DECLS @@ -80,7 +77,6 @@ import_dbus_bindings(const char *this_module_name) } c_api = PyObject_GetAttrString(_dbus_bindings_module, "_C_API"); if (c_api == NULL) return -1; -#ifdef PY3 dbus_bindings_API = NULL; if (PyCapsule_IsValid(c_api, PYDBUS_CAPSULE_NAME)) { dbus_bindings_API = (_dbus_py_func_ptr *)PyCapsule_GetPointer( @@ -91,17 +87,6 @@ import_dbus_bindings(const char *this_module_name) PyErr_SetString(PyExc_RuntimeError, "C API is not a PyCapsule"); return -1; } -#else - if (PyCObject_Check(c_api)) { - dbus_bindings_API = (_dbus_py_func_ptr *)PyCObject_AsVoidPtr(c_api); - } - else { - Py_DECREF(c_api); - PyErr_SetString(PyExc_RuntimeError, "C API is not a PyCObject"); - return -1; - } - Py_DECREF (c_api); -#endif count = *(int *)dbus_bindings_API[0]; if (count < DBUS_BINDINGS_API_COUNT) { PyErr_Format(PyExc_RuntimeError, diff --git a/test/cross-test-client.py b/test/cross-test-client.py index fe196ce..4c25499 100755 --- a/test/cross-test-client.py +++ b/test/cross-test-client.py @@ -35,24 +35,13 @@ except ImportError: from dbus import ( Array, Boolean, Byte, ByteArray, Double, Int16, Int32, Int64, Interface, SessionBus, String, UInt16, UInt32, UInt64) -from dbus._compat import is_py2, is_py3 import dbus.glib -if is_py2: - from dbus import UTF8String - from crosstest import ( CROSS_TEST_BUS_NAME, CROSS_TEST_PATH, INTERFACE_CALLBACK_TESTS, INTERFACE_SIGNAL_TESTS, INTERFACE_SINGLE_TESTS, INTERFACE_TESTS, SignalTestsImpl) -if is_py3: - def make_long(n): - return n -else: - def make_long(n): - return long(n) - logging.basicConfig() logging.getLogger().setLevel(1) @@ -246,8 +235,6 @@ class Client(SignalTestsImpl): # Main tests self.assert_method_eq(INTERFACE_TESTS, String('foo', variant_level=1), 'Identity', String('foo')) - if is_py2: - self.assert_method_eq(INTERFACE_TESTS, String('foo', variant_level=1), 'Identity', UTF8String('foo')) self.assert_method_eq(INTERFACE_TESTS, Byte(42, variant_level=1), 'Identity', Byte(42)) self.assert_method_eq(INTERFACE_TESTS, Byte(42, variant_level=23), 'Identity', Byte(42, variant_level=23)) self.assert_method_eq(INTERFACE_TESTS, Double(42.5, variant_level=1), 'Identity', 42.5) @@ -271,11 +258,10 @@ class Client(SignalTestsImpl): for i in (-0x7fffffff-1, 0, 42, 0x7fffffff): self.assert_method_eq(INTERFACE_TESTS, i, 'IdentityInt32', Int32(i)) for i in (0, 42, 0xffffffff): - i = make_long(i) self.assert_method_eq(INTERFACE_TESTS, i, 'IdentityUInt32', UInt32(i)) MANY = 1 for n in (0x8000, 0x10000, 0x10000, 0x10000): - MANY *= make_long(n) + MANY *= n for i in (-MANY, 0, 42, MANY-1): self.assert_method_eq(INTERFACE_TESTS, i, 'IdentityInt64', Int64(i)) for i in (0, 42, 2*MANY - 1): diff --git a/test/cross-test-server.py b/test/cross-test-server.py index 3799937..96a315a 100755 --- a/test/cross-test-server.py +++ b/test/cross-test-server.py @@ -35,7 +35,6 @@ except ImportError: import dbus.glib from dbus import SessionBus from dbus.service import BusName -from dbus._compat import is_py2 from crosstest import ( CROSS_TEST_BUS_NAME, CROSS_TEST_PATH, INTERFACE_CALLBACK_TESTS, @@ -226,12 +225,7 @@ class TestsImpl(dbus.service.Object): logger.info('Sum of %r is %r', input, x) return x - - kwargs = {} - if is_py2: - kwargs['utf8_strings'] = True - - @dbus.service.method(INTERFACE_TESTS, 'a{ss}', 'a{sas}', **kwargs) + @dbus.service.method(INTERFACE_TESTS, 'a{ss}', 'a{sas}') def InvertMapping(self, input): tested_things.add(INTERFACE_TESTS + '.InvertMapping') output = dbus.Dictionary({}) @@ -276,8 +270,7 @@ class TestsImpl(dbus.service.Object): @dbus.service.method(INTERFACE_TESTS, 'st', '', connection_keyword='conn', - async_callbacks=('reply_cb', 'error_cb'), - **kwargs) + async_callbacks=('reply_cb', 'error_cb')) def Trigger(self, object, parameter, conn=None, reply_cb=None, error_cb=None): assert isinstance(object, str) @@ -328,17 +321,13 @@ if __name__ == '__main__': loop = GLib.MainLoop() obj = Server(bus_name, CROSS_TEST_PATH, loop.quit) objects[CROSS_TEST_PATH] = obj - kwargs = {} - if is_py2: - kwargs['utf8_strings'] = True bus.add_signal_receiver(obj.triggered_by_client, signal_name='Trigger', dbus_interface=INTERFACE_SIGNAL_TESTS, named_service=None, path=None, sender_keyword='sender', - path_keyword='sender_path', - **kwargs) + path_keyword='sender_path') logger.info("running...") loop.run() diff --git a/test/dbus_py_test.c b/test/dbus_py_test.c index 7f8f996..6ff8547 100644 --- a/test/dbus_py_test.c +++ b/test/dbus_py_test.c @@ -28,11 +28,7 @@ #include #include -#ifdef PY3 PyMODINIT_FUNC PyInit_dbus_py_test(void); -#else -PyMODINIT_FUNC initdbus_py_test(void); -#endif #if defined(__GNUC__) # if __GNUC__ >= 3 @@ -119,7 +115,6 @@ static PyMethodDef module_functions[] = { {NULL, NULL, 0, NULL} }; -#ifdef PY3 PyMODINIT_FUNC PyInit_dbus_py_test(void) { @@ -139,16 +134,5 @@ PyInit_dbus_py_test(void) return PyModule_Create(&moduledef); } -#else -PyMODINIT_FUNC -initdbus_py_test(void) -{ - PyObject *this_module; - - if (import_dbus_bindings("dbus_py_test") < 0) return; - this_module = Py_InitModule3 ("dbus_py_test", module_functions, ""); - if (!this_module) return; -} -#endif /* vim:set ft=c cino< sw=4 sts=4 et: */ diff --git a/test/test-client.py b/test/test-client.py index e486309..916ad4f 100755 --- a/test/test-client.py +++ b/test/test-client.py @@ -39,8 +39,6 @@ import dbus.lowlevel import dbus.service import dbus_test_utils -from dbus._compat import is_py2, is_py3 - try: from gi.repository import GLib except ImportError: @@ -128,16 +126,9 @@ class TestDBusBindings(unittest.TestCase): self.assertEqual(self.iface.AcceptListOfByte(b'\1\2\3', byte_arrays=True), b'\1\2\3') self.assertEqual(self.iface.AcceptByteArray(b'\1\2\3'), [1,2,3]) self.assertEqual(self.iface.AcceptByteArray(b'\1\2\3', byte_arrays=True), b'\1\2\3') - if is_py2: - self.assertTrue(isinstance(self.iface.AcceptUTF8String('abc'), unicode)) - self.assertTrue(isinstance(self.iface.AcceptUTF8String('abc', utf8_strings=True), str)) - unicode_type = (str if is_py3 else unicode) self.assertTrue(isinstance(self.iface.AcceptUnicodeString('abc'), - unicode_type)) - kwargs = {} - if is_py2: - kwargs['utf8_strings'] = True - self.assertTrue(isinstance(self.iface.AcceptUnicodeString('abc', **kwargs), str)) + str)) + self.assertTrue(isinstance(self.iface.AcceptUnicodeString('abc'), str)) def testIntrospection(self): #test introspection @@ -179,17 +170,6 @@ class TestDBusBindings(unittest.TestCase): self.assertTrue(destination.startswith(':')) self.assertEqual(message_cls, 'dbus.lowlevel.MethodCallMessage') - def testUtf8StringsSync(self): - if is_py3: - return - send_val = 'foo' - recv_val = self.iface.Echo(send_val, utf8_strings=True) - self.assertTrue(isinstance(recv_val, str)) - self.assertTrue(isinstance(recv_val, dbus.UTF8String)) - recv_val = self.iface.Echo(send_val, utf8_strings=False) - self.assertTrue(isinstance(recv_val, unicode)) - self.assertTrue(isinstance(recv_val, dbus.String)) - def testBenchmarkIntrospect(self): print("\n********* Benchmark Introspect ************") a = time.time() @@ -204,7 +184,6 @@ class TestDBusBindings(unittest.TestCase): failures = [] report = [] main_loop = GLib.MainLoop() - unicode_type = (str if is_py3 else unicode) def message_filter(conn, m): print('Message filter received message: %r, %r' % (m, m.get_args_list())) @@ -213,7 +192,7 @@ class TestDBusBindings(unittest.TestCase): failures.append('Message filter called on unexpected bus') for a in m.get_args_list(): - if isinstance(a, unicode_type): + if isinstance(a, str): if SHOULD_NOT_HAPPEN in a: failures.append('Had an unexpected reply') elif a == 'TestNoReply report': @@ -263,9 +242,7 @@ class TestDBusBindings(unittest.TestCase): self.expected_result = expected_result self.do_exit = do_exit self.test_controler = test_controler - if is_py2: - self.utf8 = kwargs['utf8'] - elif 'utf8' in kwargs: + if 'utf8' in kwargs: raise TypeError("unexpected keyword argument 'utf8'") def callback(self, val): @@ -275,13 +252,6 @@ class TestDBusBindings(unittest.TestCase): self.test_controler.assertEqual(val, self.expected_result) self.test_controler.assertEqual(val.variant_level, 1) - if is_py2: - if self.utf8 and not isinstance(val, dbus.UTF8String): - failures.append('%r should have been utf8 but was not' % val) - return - elif not self.utf8 and isinstance(val, dbus.UTF8String): - failures.append('%r should not have been utf8' % val) - return except Exception as e: failures.append("%s:\n%s" % (e.__class__, e)) @@ -295,17 +265,10 @@ class TestDBusBindings(unittest.TestCase): last_type = test_types_vals[-1] for send_val in test_types_vals: print("Testing %s" % str(send_val)) - kwargs = {} - if is_py2: - utf8 = (send_val == 'gob@gob.com') - kwargs['utf8'] = utf8 - kwargs['utf8_strings'] = utf8 - check = async_check(self, send_val, last_type == send_val, - **kwargs) + check = async_check(self, send_val, last_type == send_val) recv_val = self.iface.Echo(send_val, reply_handler=check.callback, - error_handler=check.error_handler, - **kwargs) + error_handler=check.error_handler) main_loop.run() if failures: self.assertTrue(False, failures) diff --git a/test/test-exception-py2.py b/test/test-exception-py2.py deleted file mode 100755 index a8427c6..0000000 --- a/test/test-exception-py2.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# SPDX-License-Identifier: MIT - -import sys -import unittest - -import dbus -import dbus_test_utils - -# from test-service.py -class ServiceError(dbus.DBusException): - """Exception representing a normal "environmental" error""" - include_traceback = False - _dbus_error_name = 'com.example.Networking.ServerError' - - -class DBusExceptionTestCase(unittest.TestCase): - """Test the DBusException str/unicode behavior with py2""" - - def test_dbus_exception_normal(self): - """Test the normal Exception behavior""" - e = dbus.exceptions.DBusException("baaa") - msg = e.get_dbus_message() - self.assertEqual(msg, u"baaa") - - def test_dbus_exception_unicode(self): - """Test that DBusExceptions that take a py2 unicode work""" - e = dbus.exceptions.DBusException(u"bäää") - msg = e.get_dbus_message() - self.assertEqual(msg, u"bäää") - - def test_dbus_exception_convert_str(self): - """Test that converting a DBusException to str() works as expected""" - e = dbus.exceptions.DBusException(u"bxxx") - self.assertEqual(str(e), "bxxx") - - def test_dbus_exception_convert_str_fail(self): - """Test that a non-ascii Exception fails to convert to str""" - if sys.getdefaultencoding() == 'ascii': - self.assertRaises(UnicodeEncodeError, - lambda: str(dbus.exceptions.DBusException(u"bä"))) - else: - self.skipTest("you're using a weird non-ascii " - "sys.getdefaultencoding()") - - def test_dbus_exception_convert_unicode(self): - """Test that converting a DBusEception to unicode works""" - e = dbus.exceptions.DBusException(u"bäää") - self.assertEqual(e.get_dbus_message(), u"bäää") - self.assertEqual(e.__unicode__(), u"bäää") - self.assertEqual(unicode(e), u"bäää") - - def test_subclass_exception_unicode(self): - """Test that DBusExceptions that take a py2 unicode work""" - e = ServiceError(u"bäää") - msg = e.get_dbus_message() - self.assertEqual(msg, u"bäää") - self.assertEqual( - unicode(e), u"com.example.Networking.ServerError: bäää") - - -if __name__ == "__main__": - dbus_test_utils.main() diff --git a/test/test-p2p.py b/test/test-p2p.py index efe1041..68f7f71 100755 --- a/test/test-p2p.py +++ b/test/test-p2p.py @@ -37,8 +37,6 @@ import dbus.service import dbus.types import dbus_test_utils -from dbus._compat import is_py2 - try: from gi.repository import GLib except ImportError: @@ -62,15 +60,10 @@ class TestDBusBindings(unittest.TestCase): # using dbus.bus.BusConnection! conn = dbus.connection.Connection( os.environ['DBUS_SESSION_BUS_ADDRESS']) - kwargs = {} - if is_py2: - kwargs['utf8_strings'] = True unique = conn.call_blocking('org.freedesktop.DBus', '/org/freedesktop/DBus', 'org.freedesktop.DBus', 'Hello', - '', (), **kwargs) - if is_py2: - self.assertTrue(unique.__class__ == dbus.UTF8String, repr(unique)) + '', ()) self.assertTrue(unique.startswith(':'), unique) conn.set_unique_name(unique) return conn, unique @@ -112,12 +105,8 @@ class TestDBusBindings(unittest.TestCase): def testSetUniqueName(self): conn, unique = self.get_conn_and_unique() - kwargs = {} - if is_py2: - kwargs['utf8_strings'] = True ret = conn.call_blocking(NAME, OBJECT, IFACE, - 'MethodExtraInfoKeywords', '', (), - **kwargs) + 'MethodExtraInfoKeywords', '', ()) self.assertEqual(ret, (unique, OBJECT, NAME, 'dbus.lowlevel.MethodCallMessage')) diff --git a/test/test-service.py b/test/test-service.py index 5440dfa..f0f2819 100755 --- a/test/test-service.py +++ b/test/test-service.py @@ -52,7 +52,6 @@ import random from dbus.gi_service import ExportedGObject from gi.repository import GLib -from dbus._compat import is_py2, is_py3 if 'DBUS_TEST_TMPDIR' in os.environ: @@ -168,14 +167,10 @@ class TestObject(dbus.service.Object, TestInterface): @dbus.service.method(IFACE, in_signature='s', out_signature='s') def AcceptUnicodeString(self, foo): - unicode_type = (str if is_py3 else unicode) - assert isinstance(foo, unicode_type), (foo, foo.__class__.__mro__) + assert isinstance(foo, str), (foo, foo.__class__.__mro__) return foo - kwargs = {} - if is_py2: - kwargs['utf8_strings'] = True - @dbus.service.method(IFACE, in_signature='s', out_signature='s', **kwargs) + @dbus.service.method(IFACE, in_signature='s', out_signature='s') def AcceptUTF8String(self, foo): assert isinstance(foo, str), (foo, foo.__class__.__mro__) return foo diff --git a/test/test-standalone.py b/test/test-standalone.py index 7ec6e47..055704e 100755 --- a/test/test-standalone.py +++ b/test/test-standalone.py @@ -40,18 +40,7 @@ import dbus import dbus.lowlevel as lowlevel import dbus.types as types import dbus_test_utils -from dbus._compat import is_py2, is_py3 -if is_py3: - def make_long(n): - return n - - UNICODE = str -else: - def make_long(n): - return long(n) - - UNICODE = unicode if 'DBUS_TEST_UNINSTALLED' in os.environ: builddir = os.path.normpath(os.environ["DBUS_TOP_BUILDDIR"]) @@ -86,10 +75,7 @@ def uni(x): supported. """ if x <= 0xFFFF: - if is_py3: - return chr(x) - else: - return unichr(x) + return chr(x) else: return struct.pack('>I', x).decode('utf_32_be') @@ -125,7 +111,6 @@ class TestTypes(unittest.TestCase): self.assertEqual(types.Byte(b'x', variant_level=2), types.Byte(ord('x'))) self.assertEqual(types.Byte(1), 1) - self.assertEqual(types.Byte(make_long(1)), 1) self.assertRaises(Exception, lambda: types.Byte(b'ab')) self.assertRaises(TypeError, types.Byte, '\x12xxxxxxxxxxxxx') self.assertEqual(str(types.Byte(b'x')), 'x') @@ -145,8 +130,6 @@ class TestTypes(unittest.TestCase): def test_integers(self): subclasses = [int] - if is_py2: - subclasses.append(long) subclasses = tuple(subclasses) # This is an API guarantee. Note that exactly which of these types # are ints and which of them are longs is *not* guaranteed. @@ -162,12 +145,6 @@ class TestTypes(unittest.TestCase): self.assertEqual(str(cls(42)), '42') self.assertIs(type(str(cls(42))), str) - if is_py2: - self.assertEqual(long(cls(42)), make_long(42)) - self.assertIs(type(long(cls(42))), long) - self.assertEqual(unicode(cls(42)), '42'.decode('ascii')) - self.assertIs(type(unicode(cls(42))), unicode) - def test_integer_limits_16(self): self.assertEqual(types.Int16(0x7fff), 0x7fff) self.assertEqual(types.Int16(-0x8000), -0x8000) @@ -178,27 +155,22 @@ class TestTypes(unittest.TestCase): def test_integer_limits_32(self): self.assertEqual(types.Int32(0x7fffffff), 0x7fffffff) - self.assertEqual(types.Int32(make_long(-0x80000000)), - make_long(-0x80000000)) - self.assertEqual(types.UInt32(make_long(0xffffffff)), - make_long(0xffffffff)) - self.assertRaises(Exception, types.Int32, make_long(0x80000000)) - self.assertRaises(Exception, types.Int32, make_long(-0x80000001)) - self.assertRaises(Exception, types.UInt32, make_long(0x100000000)) + self.assertEqual(types.Int32(-0x80000000), -0x80000000) + self.assertEqual(types.UInt32(0xffffffff), 0xffffffff) + self.assertRaises(Exception, types.Int32, 0x80000000) + self.assertRaises(Exception, types.Int32, -0x80000001) + self.assertRaises(Exception, types.UInt32, 0x100000000) def test_integer_limits_64(self): - self.assertEqual(types.Int64(make_long(0x7fffffffffffffff)), - make_long(0x7fffffffffffffff)) - self.assertEqual(types.Int64(make_long(-0x8000000000000000)), - make_long(-0x8000000000000000)) - self.assertEqual(types.UInt64(make_long(0xffffffffffffffff)), - make_long(0xffffffffffffffff)) - self.assertRaises(Exception, types.Int64, - make_long(0x8000000000000000)) - self.assertRaises(Exception, types.Int64, - make_long(-0x8000000000000001)) - self.assertRaises(Exception, types.UInt64, - make_long(0x10000000000000000)) + self.assertEqual(types.Int64(0x7fffffffffffffff), + 0x7fffffffffffffff) + self.assertEqual(types.Int64(-0x8000000000000000), + -0x8000000000000000) + self.assertEqual(types.UInt64(0xffffffffffffffff), + 0xffffffffffffffff) + self.assertRaises(Exception, types.Int64, 0x8000000000000000) + self.assertRaises(Exception, types.Int64, -0x8000000000000001) + self.assertRaises(Exception, types.UInt64, 0x10000000000000000) def test_Signature(self): self.assertRaises(Exception, types.Signature, 'a') @@ -211,31 +183,13 @@ class TestTypes(unittest.TestCase): self.assertEqual(str(types.Signature('ab')), 'ab') self.assertIs(type(str(types.Signature('ab'))), str) - if is_py2: - self.assertEqual(str(types.Signature('ab')), 'ab') - self.assertIs(type(str(types.Signature('ab'))), str) - self.assertEqual(unicode(types.Signature('ab')), 'ab'.decode('ascii')) - self.assertIs(type(unicode(types.Signature('ab'))), unicode) - def test_string(self): self.assertEqual(types.String('hello', variant_level=23), 'hello') self.assertEqual(types.String('hello', variant_level=23).variant_level, 23) - self.assertTrue(isinstance(types.String('hello'), UNICODE)) + self.assertTrue(isinstance(types.String('hello'), str)) self.assertEqual(str(types.String('hello')), 'hello') self.assertIs(type(str(types.String('hello'))), str) - if is_py2: - self.assertEqual(unicode(types.String('hello')), 'hello'.decode('ascii')) - self.assertIs(type(unicode(types.String('hello'))), unicode) - - self.assertEqual(types.UTF8String('hello', variant_level=23), 'hello') - self.assertEqual(types.UTF8String('hello', variant_level=23).variant_level, 23) - self.assertTrue(isinstance(types.UTF8String('hello'), str)) - self.assertEqual(str(types.UTF8String('hello')), 'hello') - self.assertIs(type(str(types.UTF8String('hello'))), str) - self.assertEqual(unicode(types.UTF8String('hello')), 'hello'.decode('ascii')) - self.assertIs(type(unicode(types.UTF8String('hello'))), unicode) - def test_object_path(self): self.assertRaises(Exception, types.ObjectPath, 'a') self.assertEqual(types.ObjectPath('/ab', variant_level=23), '/ab') @@ -244,10 +198,6 @@ class TestTypes(unittest.TestCase): self.assertEqual(str(types.ObjectPath('/ab')), '/ab') self.assertIs(type(str(types.ObjectPath('/ab'))), str) - if is_py2: - self.assertEqual(unicode(types.ObjectPath('/ab')), '/ab'.decode('ascii')) - self.assertIs(type(unicode(types.ObjectPath('/ab'))), unicode) - def test_boolean(self): self.assertEqual(types.Boolean(True, variant_level=23), True) self.assertEqual(types.Boolean(True, variant_level=23).variant_level, 23) @@ -260,10 +210,6 @@ class TestTypes(unittest.TestCase): self.assertIs(type(int(types.Boolean(False))), int) self.assertIs(type(int(types.Boolean(True))), int) - if is_py2: - self.assertEqual(unicode(types.Boolean(True)), '1'.decode('ascii')) - self.assertIs(type(unicode(types.Boolean(True))), unicode) - class TestMessageMarshalling(unittest.TestCase): @@ -427,8 +373,6 @@ class TestMessageMarshalling(unittest.TestCase): aeq = self.assertEqual from _dbus_bindings import Message aeq(Message.guess_signature(7), 'i') - if is_py2: - aeq(Message.guess_signature(make_long(7)), 'x') def test_guess_signature_dbus_types(self): aeq = self.assertEqual @@ -465,31 +409,20 @@ class TestMessageMarshalling(unittest.TestCase): aeq(byte.__class__, types.Byte) aeq(bytes.__class__, types.ByteArray) aeq(bytes, b'bytes') - if is_py3: - aeq(bytes[0].__class__, int) - else: - aeq(bytes[0].__class__, str) + aeq(bytes[0].__class__, int) aeq(int32.__class__, types.Int32) aeq(uint32.__class__, types.UInt32) aeq(string.__class__, types.String) aeq(variant.__class__, types.String) aeq(variant.variant_level, 1) - kwargs = {} - if is_py2: - kwargs['utf8_strings'] = True - byte, bytes, int32, uint32, string, variant = s.get_args_list( - **kwargs) + byte, bytes, int32, uint32, string, variant = s.get_args_list() aeq(byte.__class__, types.Byte) aeq(bytes.__class__, types.Array) aeq(bytes[0].__class__, types.Byte) aeq(int32.__class__, types.Int32) aeq(uint32.__class__, types.UInt32) - if is_py2: - aeq(string.__class__, types.UTF8String) aeq(string, 'str') - if is_py2: - aeq(variant.__class__, types.UTF8String) aeq(variant.variant_level, 1) aeq(variant, 'var') diff --git a/tools/ci-build.sh b/tools/ci-build.sh index e8569c3..93acf3b 100755 --- a/tools/ci-build.sh +++ b/tools/ci-build.sh @@ -58,17 +58,6 @@ if [ -n "$dbus_ci_system_python" ]; then unset VIRTUAL_ENV export PATH=/usr/bin:/bin export PYTHON="$(command -v "$dbus_ci_system_python")" - - case "$dbus_ci_system_python" in - (python-dbg|python2.7-dbg) - # This is a workaround. Python 2 doesn't have the - # LDVERSION sysconfig variable, which would give - # AX_PYTHON_DEVEL the information it needs to know - # that it should link -lpython2.7_d and not - # -lpython2.7. - export PYTHON_LIBS="-lpython2.7_d" - ;; - esac fi NOCONFIGURE=1 ./autogen.sh @@ -94,7 +83,7 @@ $make -C "$builddir" distcheck $make -C "$builddir" install ( cd "$prefix" && find . -ls ) -dbus_ci_pyversion="$(${PYTHON:-python} -c 'import distutils.sysconfig; print(distutils.sysconfig.get_config_var("VERSION"))')" +dbus_ci_pyversion="$(${PYTHON:-python3} -c 'import sysconfig; print(sysconfig.get_config_var("VERSION"))')" export PYTHONPATH="$prefix/lib/python$dbus_ci_pyversion/site-packages:$PYTHONPATH" export XDG_DATA_DIRS="$prefix/share:/usr/local/share:/usr/share" gnome-desktop-testing-runner dbus-python diff --git a/tools/ci-install.sh b/tools/ci-install.sh index dd554c6..81be157 100755 --- a/tools/ci-install.sh +++ b/tools/ci-install.sh @@ -76,17 +76,6 @@ if [ -n "$ci_docker" ]; then fi if [ -n "${dbus_ci_system_python-}" ]; then - if [ -z "${dbus_ci_system_python_module_prefix-}" ]; then - case "$dbus_ci_system_python}" in - (python3*) - dbus_ci_system_python_module_prefix=python3- - ;; - (*) - dbus_ci_system_python_module_prefix=python- - ;; - esac - fi - if [ -z "${dbus_ci_system_python_module_suffix-}" ]; then case "$dbus_ci_system_python}" in (*-dbg) @@ -138,10 +127,10 @@ case "$ci_distro" in sudo apt-get -qq -y install \ ${dbus_ci_system_python} \ ${dbus_ci_system_python%-dbg}-dev \ - ${dbus_ci_system_python_module_prefix}docutils \ - ${dbus_ci_system_python_module_prefix}gi${dbus_ci_system_python_module_suffix} \ - ${dbus_ci_system_python_module_prefix}pip \ - ${dbus_ci_system_python_module_prefix}setuptools \ + python3-docutils \ + python3-gi${dbus_ci_system_python_module_suffix} \ + python3-pip \ + python3-setuptools \ ${NULL} if [ "$dbus_ci_system_python" = python ]; then @@ -153,10 +142,8 @@ case "$ci_distro" in ;; (*) - if [ "${dbus_ci_system_python_module_prefix}" = python3- ]; then - $sudo apt-get -qq -y install python3-tap - have_system_tappy=yes - fi + $sudo apt-get -qq -y install python3-tap + have_system_tappy=yes ;; esac @@ -166,8 +153,8 @@ case "$ci_distro" in (*) $sudo apt-get -qq -y install \ - ${dbus_ci_system_python_module_prefix}sphinx \ - ${dbus_ci_system_python_module_prefix}sphinx-rtd-theme \ + python3-sphinx \ + python3-sphinx-rtd-theme \ ${NULL} have_system_sphinx=yes ;; -- cgit v1.2.1