Commit a6799b24 authored by Christoph Reiter's avatar Christoph Reiter 馃悕
Browse files

Remove all Python 2 Python code

parent 9cdbc56f
# -*- coding: utf-8 -*-
extensions = [
'sphinx.ext.todo',
'sphinx.ext.intersphinx',
......
#!/usr/bin/env python
# coding=utf-8
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
#
......
......@@ -18,8 +18,6 @@
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
from __future__ import absolute_import
# support overrides in different directories than our gi module
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
......@@ -44,7 +42,6 @@ from ._gi import _API
from ._gi import Repository
from ._gi import PyGIDeprecationWarning
from ._gi import PyGIWarning
from ._compat import string_types
_API = _API # pyflakes
PyGIDeprecationWarning = PyGIDeprecationWarning
......@@ -111,7 +108,7 @@ def require_version(namespace, version):
"""
repository = Repository.get_default()
if not isinstance(version, string_types):
if not isinstance(version, str):
raise ValueError('Namespace version needs to be a string.')
if namespace in repository.get_loaded_namespaces():
......
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, see <http://www.gnu.org/licenses/>.
import sys
PY2 = PY3 = False
if sys.version_info[0] == 2:
PY2 = True
from StringIO import StringIO
StringIO
from UserList import UserList
UserList
long_ = eval("long")
integer_types = eval("(int, long)")
string_types = eval("(basestring,)")
text_type = eval("unicode")
reload = eval("reload")
xrange = eval("xrange")
cmp = eval("cmp")
exec("def reraise(tp, value, tb):\n raise tp, value, tb")
else:
PY3 = True
from io import StringIO
StringIO
from collections import UserList
UserList
long_ = int
integer_types = (int,)
string_types = (str,)
text_type = str
from importlib import reload
reload
xrange = range
cmp = lambda a, b: (a > b) - (a < b)
def reraise(tp, value, tb):
raise tp(value).with_traceback(tb)
......@@ -32,7 +32,6 @@ import optparse
from optparse import OptParseError, OptionError, OptionValueError, \
BadOptionError, OptionConflictError
from .module import get_introspection_module
from ._compat import string_types
from gi import _gi
from gi._error import GError
......@@ -230,7 +229,7 @@ class OptionGroup(optparse.OptionGroup):
def set_values_to_defaults(self):
for option in self.option_list:
default = self.defaults.get(option.dest)
if isinstance(default, string_types):
if isinstance(default, str):
opt_str = option.get_opt_string()
self.defaults[option.dest] = option.check_value(
opt_str, default)
......@@ -310,7 +309,7 @@ class OptionParser(optparse.OptionParser):
return context
def add_option_group(self, *args, **kwargs):
if isinstance(args[0], string_types):
if isinstance(args[0], str):
optparse.OptionParser.add_option_group(self,
OptionGroup(self, *args, **kwargs))
return
......
# -*- coding: utf-8 -*-
# Copyright 2017 Christoph Reiter
#
# This library is free software; you can redistribute it and/or
......@@ -17,7 +16,6 @@
from __future__ import print_function
import os
import sys
import socket
import signal
import threading
......@@ -63,8 +61,6 @@ def wakeup_on_signal():
shortly so that any registered Python signal handlers registered through
signal.signal() can run.
Works on Windows but needs Python 3.5+.
In case the wrapped function is not called from the main thread it will be
called as is and it will not wake up the default loop for signals.
"""
......@@ -77,16 +73,6 @@ def wakeup_on_signal():
from gi.repository import GLib
# On Windows only Python 3.5+ supports passing sockets to set_wakeup_fd
set_wakeup_fd_supports_socket = (
os.name != "nt" or sys.version_info[:2] >= (3, 5))
# On Windows only Python 3 has an implementation of socketpair()
has_socketpair = hasattr(socket, "socketpair")
if not has_socketpair or not set_wakeup_fd_supports_socket:
yield
return
read_socket, write_socket = socket.socketpair()
with closing(read_socket), closing(write_socket):
......
......@@ -18,7 +18,6 @@
# License along with this library; if not, see <http://www.gnu.org/licenses/>.
from . import _gi
from ._compat import string_types, long_
from ._constants import \
TYPE_NONE, TYPE_INTERFACE, TYPE_CHAR, TYPE_UCHAR, \
TYPE_BOOLEAN, TYPE_INT, TYPE_UINT, TYPE_LONG, \
......@@ -93,8 +92,6 @@ class Property(object):
self.value = value
"""
_type_from_pytype_lookup = {
# Put long_ first in case long_ and int are the same so int clobbers long_
long_: TYPE_LONG,
int: TYPE_INT,
bool: TYPE_BOOLEAN,
float: TYPE_DOUBLE,
......@@ -152,11 +149,11 @@ class Property(object):
self.default = self._get_default(default)
self._check_default()
if not isinstance(nick, string_types):
if not isinstance(nick, str):
raise TypeError("nick must be a string")
self.nick = nick
if not isinstance(blurb, string_types):
if not isinstance(blurb, str):
raise TypeError("blurb must be a string")
self.blurb = blurb
# Always clobber __doc__ with blurb even if blurb is empty because
......
......@@ -21,7 +21,6 @@
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
from __future__ import absolute_import
import sys
import warnings
import importlib
......
......@@ -44,7 +44,6 @@ headers = [
install_headers(headers, subdir : 'pygobject-@0@'.format(platform_version))
python_sources = [
'_compat.py',
'_constants.py',
'docstring.py',
'_error.py',
......
......@@ -20,16 +20,8 @@
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
from __future__ import absolute_import
import importlib
try:
maketrans = ''.maketrans
except AttributeError:
# fallback for Python 2
from string import maketrans
import gi
from ._gi import \
......@@ -155,7 +147,7 @@ class IntrospectionModule(object):
# Don't use upper() here to avoid locale specific
# identifier conversion (e. g. in Turkish 'i'.upper() == 'i')
# see https://bugzilla.gnome.org/show_bug.cgi?id=649165
ascii_upper_trans = maketrans(
ascii_upper_trans = ''.maketrans(
'abcdefgjhijklmnopqrstuvwxyz',
'ABCDEFGJHIJKLMNOPQRSTUVWXYZ')
for value_info in info.get_values():
......
......@@ -29,8 +29,6 @@ import gi.module
from gi.overrides import override, deprecated_attr
from gi.repository import GLib
from gi import PyGIDeprecationWarning
from gi._compat import PY2, text_type
from gi import _propertyhelper as propertyhelper
from gi import _signalhelper as signalhelper
from gi import _gi
......@@ -239,15 +237,8 @@ class Value(GObjectModule.Value):
self.set_uchar(py_value)
elif gtype == TYPE_STRING:
if not isinstance(py_value, str) and py_value is not None:
if PY2:
if isinstance(py_value, text_type):
py_value = py_value.encode('UTF-8')
else:
raise TypeError("Expected string or unicode but got %s%s" %
(py_value, type(py_value)))
else:
raise TypeError("Expected string but got %s%s" %
(py_value, type(py_value)))
raise TypeError("Expected string but got %s%s" %
(py_value, type(py_value)))
_gi._gvalue_set(self, py_value)
elif gtype == TYPE_PARAM:
self.set_param(py_value)
......
......@@ -295,9 +295,6 @@ if GDK2 or GDK3:
for method_info in Gdk.Event.__info__.get_methods():
name = method_info.get_name()
event_method = getattr(Gdk.Event, name)
# python2 we need to use the __func__ attr to avoid internal
# instance checks
event_method = getattr(event_method, '__func__', event_method)
# use the _gsuccess_mask decorator if this method is whitelisted
if name in gsuccess_mask_funcs:
......
......@@ -23,7 +23,6 @@ import warnings
from .._ossighelper import wakeup_on_signal, register_sigint_fallback
from ..overrides import override, deprecated_init
from ..module import get_introspection_module
from .._compat import xrange
from gi._gi import pygobject_new_full
from gi import PyGIWarning
......@@ -427,7 +426,7 @@ class ListModel(Gio.ListModel):
def __getitem__(self, key):
if isinstance(key, slice):
return [self.get_item(i) for i in xrange(*key.indices(len(self)))]
return [self.get_item(i) for i in range(*key.indices(len(self)))]
elif isinstance(key, int):
if key < 0:
key += len(self)
......@@ -454,7 +453,7 @@ class ListModel(Gio.ListModel):
return self.get_n_items()
def __iter__(self):
for i in xrange(len(self)):
for i in range(len(self)):
yield self.get_item(i)
......@@ -504,7 +503,7 @@ class ListStore(Gio.ListStore):
elif step == -1:
_list_store_splice(self, stop + 1, max(start - stop, 0), [])
else:
for i in sorted(xrange(start, stop, step), reverse=True):
for i in sorted(range(start, stop, step), reverse=True):
self.remove(i)
elif isinstance(key, int):
if key < 0:
......@@ -531,7 +530,7 @@ class ListStore(Gio.ListStore):
_list_store_splice(
self, start, max(stop - start, 0), valuelist)
else:
indices = list(xrange(start, stop, step))
indices = list(range(start, stop, step))
if len(indices) != len(valuelist):
raise ValueError
......
......@@ -21,18 +21,13 @@
import sys
import warnings
if sys.version_info[0] == 2:
import collections as abc
else:
from collections import abc
from collections import abc
from gi.repository import GObject
from .._ossighelper import wakeup_on_signal, register_sigint_fallback
from .._gtktemplate import Template
from ..overrides import override, strip_boolean_result, deprecated_init
from ..module import get_introspection_module
from .._compat import string_types
from gi import PyGIDeprecationWarning
......@@ -409,7 +404,7 @@ if Gtk._version in ("2.0", "3.0"):
class UIManager(Gtk.UIManager):
def add_ui_from_string(self, buffer):
if not isinstance(buffer, string_types):
if not isinstance(buffer, str):
raise TypeError('buffer must be a string')
length = _get_utf8_length(buffer)
......@@ -463,7 +458,7 @@ if Gtk._version in ("2.0", "3.0"):
def _get_utf8_length(string):
assert isinstance(string, string_types)
assert isinstance(string, str)
if not isinstance(string, bytes):
string = string.encode("utf-8")
return len(string)
......@@ -485,7 +480,7 @@ class Builder(Gtk.Builder):
self.connect_signals_full(_builder_connect_callback, obj_or_map)
def add_from_string(self, buffer):
if not isinstance(buffer, string_types):
if not isinstance(buffer, str):
raise TypeError('buffer must be a string')
length = _get_utf8_length(buffer)
......@@ -493,7 +488,7 @@ class Builder(Gtk.Builder):
return Gtk.Builder.add_from_string(self, buffer, length)
def add_objects_from_string(self, buffer, object_ids):
if not isinstance(buffer, string_types):
if not isinstance(buffer, str):
raise TypeError('buffer must be a string')
length = _get_utf8_length(buffer)
......@@ -759,7 +754,7 @@ class TextBuffer(Gtk.TextBuffer):
Gtk.TextBuffer.set_text(self, text, length)
def insert(self, iter, text, length=-1):
if not isinstance(text, string_types):
if not isinstance(text, str):
raise TypeError('text must be a string, not %s' % type(text))
Gtk.TextBuffer.insert(self, iter, text, length)
......@@ -788,7 +783,7 @@ class TextBuffer(Gtk.TextBuffer):
self.insert_with_tags(iter, text, *tag_objs)
def insert_at_cursor(self, text, length=-1):
if not isinstance(text, string_types):
if not isinstance(text, str):
raise TypeError('text must be a string, not %s' % type(text))
Gtk.TextBuffer.insert_at_cursor(self, text, length)
......@@ -1209,7 +1204,7 @@ class TreePath(Gtk.TreePath):
def __new__(cls, path=0):
if isinstance(path, int):
path = str(path)
elif not isinstance(path, string_types):
elif not isinstance(path, str):
path = ":".join(str(val) for val in path)
if len(path) == 0:
......
from __future__ import absolute_import
import warnings
from gi import PyGIDeprecationWarning
......
......@@ -18,8 +18,6 @@
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
from __future__ import absolute_import
import sys
from ..importer import DynamicImporter
......
......@@ -20,9 +20,6 @@
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
from __future__ import absolute_import
import warnings
import re
from ._constants import TYPE_INVALID
......@@ -290,19 +287,7 @@ def mro(C):
# in __mro__ at each point. Therefore at this point we know that
# we already have our base class MRO's available to us, there is
# no need for us to (re)calculate them.
if hasattr(base, '__mro__'):
bases_of_subclasses += [list(base.__mro__)]
else:
warnings.warn('Mixin class %s is an old style class, please '
'update this to derive from "object".' % base,
RuntimeWarning)
# For old-style classes (Python2 only), the MRO is not
# easily accessible. As we do need it here, we calculate
# it via recursion, according to the C3 algorithm. Using C3
# for old style classes deviates from Python's own behaviour,
# but visible effects here would be a corner case triggered by
# questionable design.
bases_of_subclasses += [mro(base)]
bases_of_subclasses += [list(base.__mro__)]
bases_of_subclasses += [list(C.__bases__)]
while bases_of_subclasses:
......
......@@ -34,10 +34,10 @@ a well behaved PyGTK application mostly unmodified on top of PyGI.
import sys
import warnings
from collections import UserList
import gi
from gi.repository import GObject
from gi import _compat
_patches = []
......@@ -149,10 +149,6 @@ def _disable_all():
sys.modules[name] = old_value
del _module_patches[:]
_compat.reload(sys)
if _compat.PY2:
sys.setdefaultencoding('ascii')
def enable_gtk(version='3.0'):
if _check_enabled("gtk", version):
......@@ -161,11 +157,6 @@ def enable_gtk(version='3.0'):
if version == "4.0":
raise ValueError("version 4.0 not supported")
# set the default encoding like PyGTK
_compat.reload(sys)
if _compat.PY2:
sys.setdefaultencoding('utf-8')
# atk
gi.require_version('Atk', '1.0')
from gi.repository import Atk
......@@ -429,11 +420,11 @@ def enable_gtk(version='3.0'):
orig_size_request = Gtk.Widget.size_request
def size_request(widget):
class SizeRequest(_compat.UserList):
class SizeRequest(UserList):
def __init__(self, req):
self.height = req.height
self.width = req.width
_compat.UserList.__init__(self, [self.width, self.height])
UserList.__init__(self, [self.width, self.height])
return SizeRequest(orig_size_request(widget))
_patch(Gtk.Widget, "size_request", size_request)
_patch(Gtk.Widget, "hide_all", Gtk.Widget.hide)
......
......@@ -217,11 +217,7 @@ def pkg_config_version_check(pkg_name, version):
def pkg_config_parse(opt, pkg_name):
ret = _run_pkg_config_or_exit(pkg_name, [opt, pkg_name])
if sys.version_info[0] == 3:
output = ret.decode()
else:
output = ret
output = ret.decode()
opt = opt[-2:]
return [x.lstrip(opt) for x in output.split()]
......@@ -874,23 +870,13 @@ def get_pycairo_include_dir():
location = os.path.dirname(os.path.abspath(cairo.__path__[0]))
log.info("pycairo: found %r" % location)
def samefile(src, dst):
# Python 2 on Windows doesn't have os.path.samefile, so we have to
# provide a fallback
if hasattr(os.path, "samefile"):
return os.path.samefile(src, dst)
os.stat(src)
os.stat(dst)
return (os.path.normcase(os.path.abspath(src)) ==
os.path.normcase(os.path.abspath(dst)))
def get_sys_path(location, name):
# Returns the sysconfig path for a distribution, or None
for scheme in sysconfig.get_scheme_names():
for path_type in ["platlib", "purelib"]:
path = sysconfig.get_path(path_type, scheme)
try:
if samefile(path, location):
if os.path.samefile(path, location):
return sysconfig.get_path(name, scheme)
except EnvironmentError:
pass
......@@ -998,11 +984,6 @@ def add_ext_compiler_flags(ext, compiler, _cache={}):
"-Wwrite-strings",
]
if sys.version_info[0] == 2:
args += [
"-Wdeclaration-after-statement",
]
args += [
"-Wno-incompatible-pointer-types-discards-qualifiers",
"-Wno-missing-field-initializers",
......
from __future__ import absolute_import
import os
import sys
import unittest
......@@ -34,12 +32,8 @@ sys.meta_path.insert(0, GIImport())
def init_test_environ():
# this was renamed in Python 3, provide backwards compatible name
if sys.version_info[:2] == (2, 7):
unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp
if sys.version_info[0] == 3:
unittest.TestCase.assertRegexpMatches = unittest.TestCase.assertRegex
unittest.TestCase.assertRaisesRegexp = unittest.TestCase.assertRaisesRegex
unittest.TestCase.assertRegexpMatches = unittest.TestCase.assertRegex
unittest.TestCase.assertRaisesRegexp = unittest.TestCase.assertRaisesRegex
def dbus_launch_session():
if os.name == "nt" or sys.platform == "darwin":
......@@ -52,8 +46,7 @@ def init_test_environ():
except (subprocess.CalledProcessError, OSError):
return (-1, "")
else:
if sys.version_info[0] == 3:
out = out.decode("utf-8")
out = out.decode("utf-8")
addr, pid = out.splitlines()
return int(pid), addr
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment