Skip to content

Commit

Permalink
Remove all Python 2 support
Browse files Browse the repository at this point in the history
* Removed all __future__ imports from code
* Removed all six dependencies
* Removed all future_builtins imports
* Removed all Python 2 related code

Closes: deluge-torrent#325
  • Loading branch information
DjLegolas authored and cas-- committed Dec 28, 2021
1 parent ff309ea commit 897955f
Show file tree
Hide file tree
Showing 259 changed files with 87 additions and 818 deletions.
7 changes: 1 addition & 6 deletions .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ callbacks=cb_,_cb

# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,future.builtins,future_builtins
redefining-builtins-modules=


[TYPECHECK]
Expand Down Expand Up @@ -359,11 +359,6 @@ known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant

# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no


[DESIGN]

Expand Down
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Changelog

## 2.0.6 (WIP)
## 2.1.0 (WIP)

- Removed Python 2 support.

## 2.0.5 (2021-12-15)

Expand Down
3 changes: 0 additions & 3 deletions DEPENDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ All modules will require the [common](#common) section dependencies.
- [rencode] _>= 1.0.2_ - Encoding library.
- [PyXDG] - Access freedesktop.org standards for \*nix.
- [xdg-utils] - Provides xdg-open for \*nix.
- [six]
- [zope.interface]
- [chardet] - Optional: Encoding detection.
- [setproctitle] - Optional: Renaming processes.
Expand Down Expand Up @@ -81,14 +80,12 @@ All modules will require the [common](#common) section dependencies.
[distro]: https://github.com/nir0s/distro
[pywin32]: https://github.com/mhammond/pywin32
[certifi]: https://pypi.org/project/certifi/
[py2-ipaddress]: https://pypi.org/project/py2-ipaddress/
[dbus-python]: https://pypi.org/project/dbus-python/
[setproctitle]: https://pypi.org/project/setproctitle/
[gtkosxapplication]: https://github.com/jralls/gtk-mac-integration
[chardet]: https://chardet.github.io/
[rencode]: https://github.com/aresch/rencode
[pyxdg]: https://www.freedesktop.org/wiki/Software/pyxdg/
[six]: https://pythonhosted.org/six/
[xdg-utils]: https://www.freedesktop.org/wiki/Software/xdg-utils/
[gtk+]: https://www.gtk.org/
[pycairo]: https://cairographics.org/pycairo/
Expand Down
2 changes: 0 additions & 2 deletions deluge/_libtorrent.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
>>> from deluge._libtorrent import lt
"""
from __future__ import unicode_literals

from deluge.common import VersionSplit, get_version
from deluge.error import LibtorrentImportError

Expand Down
2 changes: 0 additions & 2 deletions deluge/argparserbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
# See LICENSE for more details.
#

from __future__ import unicode_literals

import argparse
import logging
import os
Expand Down
12 changes: 1 addition & 11 deletions deluge/bencode.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,7 @@
# License.

# Written by Petru Paler
# Updated by Calum Lind to support both Python 2 and Python 3.

from __future__ import unicode_literals

from sys import version_info

PY2 = version_info.major == 2
# Updated by Calum Lind to support Python 3.


class BTFailure(Exception):
Expand Down Expand Up @@ -146,10 +140,6 @@ def encode_dict(x, r):
encode_func[bool] = encode_bool
encode_func[str] = encode_string
encode_func[bytes] = encode_bytes
if PY2:
encode_func[long] = encode_int # noqa: F821
encode_func[str] = encode_bytes
encode_func[unicode] = encode_string # noqa: F821


def bencode(x):
Expand Down
83 changes: 22 additions & 61 deletions deluge/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
#

"""Common functions for various parts of Deluge to use."""
from __future__ import division, print_function, unicode_literals

import base64
import binascii
import functools
Expand All @@ -27,6 +25,8 @@
from contextlib import closing
from datetime import datetime
from io import BytesIO, open
from urllib.parse import unquote_plus, urljoin
from urllib.request import pathname2url

import pkg_resources

Expand All @@ -38,14 +38,6 @@
except ImportError:
chardet = None

try:
from urllib.parse import unquote_plus, urljoin
from urllib.request import pathname2url
except ImportError:
# PY2 fallback
from urllib import pathname2url, unquote_plus # pylint: disable=ungrouped-imports
from urlparse import urljoin # pylint: disable=ungrouped-imports

# Windows workaround for HTTPS requests requiring certificate authority bundle.
# see: https://twistedmatrix.com/trac/ticket/9209
if platform.system() in ('Windows', 'Microsoft'):
Expand Down Expand Up @@ -84,8 +76,6 @@
DBUS_FM_ID = 'org.freedesktop.FileManager1'
DBUS_FM_PATH = '/org/freedesktop/FileManager1'

PY2 = sys.version_info.major == 2


def get_version():
"""The program version from the egg metadata.
Expand All @@ -111,10 +101,8 @@ def get_default_config_dir(filename=None):
def save_config_path(resource):
app_data_path = os.environ.get('APPDATA')
if not app_data_path:
try:
import winreg
except ImportError:
import _winreg as winreg # For Python 2.
import winreg

hkey = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders',
Expand Down Expand Up @@ -178,8 +166,8 @@ def archive_files(arc_name, filepaths, message=None, rotate=10):

from deluge.configmanager import get_config_dir

# Set archive compression to lzma with bz2 fallback.
arc_comp = 'xz' if not PY2 else 'bz2'
# Set archive compression to lzma
arc_comp = 'xz'

archive_dir = os.path.join(get_config_dir(), 'archive')
timestamp = datetime.now().replace(microsecond=0).isoformat().replace(':', '-')
Expand Down Expand Up @@ -1239,11 +1227,7 @@ def set_env_variable(name, value):
http://sourceforge.net/p/gramps/code/HEAD/tree/branches/maintenance/gramps32/src/TransUtils.py
"""
# Update Python's copy of the environment variables
try:
os.environ[name] = value
except UnicodeEncodeError:
# Python 2
os.environ[name] = value.encode('utf8')
os.environ[name] = value

if windows_check():
from ctypes import cdll, windll
Expand Down Expand Up @@ -1271,45 +1255,22 @@ def set_env_variable(name, value):

def unicode_argv():
""" Gets sys.argv as list of unicode objects on any platform."""
if windows_check():
# Versions 2.x of Python don't support Unicode in sys.argv on
# Windows, with the underlying Windows API instead replacing multi-byte
# characters with '?'.
from ctypes import POINTER, byref, c_int, cdll, windll
from ctypes.wintypes import LPCWSTR, LPWSTR

get_cmd_linew = cdll.kernel32.GetCommandLineW
get_cmd_linew.argtypes = []
get_cmd_linew.restype = LPCWSTR

cmdline_to_argvw = windll.shell32.CommandLineToArgvW
cmdline_to_argvw.argtypes = [LPCWSTR, POINTER(c_int)]
cmdline_to_argvw.restype = POINTER(LPWSTR)

cmd = get_cmd_linew()
argc = c_int(0)
argv = cmdline_to_argvw(cmd, byref(argc))
if argc.value > 0:
# Remove Python executable and commands if present
start = argc.value - len(sys.argv)
return [argv[i] for i in range(start, argc.value)]
else:
# On other platforms, we have to find the likely encoding of the args and decode
# First check if sys.stdout or stdin have encoding set
encoding = getattr(sys.stdout, 'encoding') or getattr(sys.stdin, 'encoding')
# If that fails, check what the locale is set to
encoding = encoding or locale.getpreferredencoding()
# As a last resort, just default to utf-8
encoding = encoding or 'utf-8'

arg_list = []
for arg in sys.argv:
try:
arg_list.append(arg.decode(encoding))
except AttributeError:
arg_list.append(arg)
# On platforms other than Windows, we have to find the likely encoding of the args and decode
# First check if sys.stdout or stdin have encoding set
encoding = getattr(sys.stdout, 'encoding') or getattr(sys.stdin, 'encoding')
# If that fails, check what the locale is set to
encoding = encoding or locale.getpreferredencoding()
# As a last resort, just default to utf-8
encoding = encoding or 'utf-8'

arg_list = []
for arg in sys.argv:
try:
arg_list.append(arg.decode(encoding))
except AttributeError:
arg_list.append(arg)

return arg_list
return arg_list


def run_profiled(func, *args, **kwargs):
Expand Down
11 changes: 4 additions & 7 deletions deluge/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,10 @@
# See LICENSE for more details.
#

from __future__ import unicode_literals

import logging
import traceback
from collections import defaultdict

from six import string_types
from twisted.internet import reactor
from twisted.internet.defer import DeferredList, fail, maybeDeferred, succeed
from twisted.internet.task import LoopingCall, deferLater
Expand Down Expand Up @@ -325,7 +322,7 @@ def start(self, names=None):
# Start all the components if names is empty
if not names:
names = list(self.components)
elif isinstance(names, string_types):
elif isinstance(names, str):
names = [names]

def on_depends_started(result, name):
Expand Down Expand Up @@ -359,7 +356,7 @@ def stop(self, names=None):
"""
if not names:
names = list(self.components)
elif isinstance(names, string_types):
elif isinstance(names, str):
names = [names]

def on_dependents_stopped(result, name):
Expand Down Expand Up @@ -399,7 +396,7 @@ def pause(self, names=None):
"""
if not names:
names = list(self.components)
elif isinstance(names, string_types):
elif isinstance(names, str):
names = [names]

deferreds = []
Expand All @@ -425,7 +422,7 @@ def resume(self, names=None):
"""
if not names:
names = list(self.components)
elif isinstance(names, string_types):
elif isinstance(names, str):
names = [names]

deferreds = []
Expand Down
5 changes: 1 addition & 4 deletions deluge/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,15 @@
version as this will be done internally.
"""
from __future__ import unicode_literals

import json
import logging
import os
import pickle
import shutil
from codecs import getwriter
from io import open
from tempfile import NamedTemporaryFile

import six.moves.cPickle as pickle # noqa: N813

from deluge.common import JSON_FORMAT, get_default_config_dir

log = logging.getLogger(__name__)
Expand Down
2 changes: 0 additions & 2 deletions deluge/configmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
# See LICENSE for more details.
#

from __future__ import unicode_literals

import logging
import os

Expand Down
12 changes: 1 addition & 11 deletions deluge/core/alertmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,8 @@
`:mod:EventManager` for similar functionality.
"""
from __future__ import unicode_literals

import logging
import types
from types import SimpleNamespace

from twisted.internet import reactor

Expand All @@ -28,14 +26,6 @@

log = logging.getLogger(__name__)

try:
SimpleNamespace = types.SimpleNamespace # Python 3.3+
except AttributeError:

class SimpleNamespace(object): # Python 2.7
def __init__(self, **attr):
self.__dict__.update(attr)


class AlertManager(component.Component):
"""AlertManager fetches and processes libtorrent alerts"""
Expand Down
2 changes: 0 additions & 2 deletions deluge/core/authmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
# See LICENSE for more details.
#

from __future__ import unicode_literals

import logging
import os
import shutil
Expand Down
Loading

0 comments on commit 897955f

Please sign in to comment.