Uses Python 3 syntax

This is a follow up for #482, uses Python 3 syntax:
- Simplifies `super()` calls
- Removes some unused `super()` (no parent class)
- Removes `object` inheritance
- Drops `IS_PY2` logic
- Drops Python 2 imports
This commit is contained in:
Andre Miras 2020-05-06 18:50:51 +02:00
parent 6fbf225fdb
commit 2c0a79a817
5 changed files with 19 additions and 56 deletions

View file

@ -17,7 +17,7 @@ class Hostpython3Recipe(Recipe):
build_subdir = 'native-build' build_subdir = 'native-build'
def init_with_ctx(self, ctx): def init_with_ctx(self, ctx):
super(Hostpython3Recipe, self).init_with_ctx(ctx) super().init_with_ctx(ctx)
self.set_hostpython(self, "3.8") self.set_hostpython(self, "3.8")
self.ctx.so_suffix = ".cpython-38m-darwin.so" self.ctx.so_suffix = ".cpython-38m-darwin.so"
self.ctx.hostpython = join(self.ctx.dist_dir, "hostpython3", "bin", "python") self.ctx.hostpython = join(self.ctx.dist_dir, "hostpython3", "bin", "python")

View file

@ -22,7 +22,7 @@ class KivyRecipe(CythonRecipe):
pre_build_ext = True pre_build_ext = True
def get_recipe_env(self, arch): def get_recipe_env(self, arch):
env = super(KivyRecipe, self).get_recipe_env(arch) env = super().get_recipe_env(arch)
env["KIVY_SDL2_PATH"] = ":".join([ env["KIVY_SDL2_PATH"] = ":".join([
join(self.ctx.dist_dir, "include", "common", "sdl2"), join(self.ctx.dist_dir, "include", "common", "sdl2"),
join(self.ctx.dist_dir, "include", "common", "sdl2_image"), join(self.ctx.dist_dir, "include", "common", "sdl2_image"),
@ -32,7 +32,7 @@ class KivyRecipe(CythonRecipe):
def build_arch(self, arch): def build_arch(self, arch):
self._patch_setup() self._patch_setup()
super(KivyRecipe, self).build_arch(arch) super().build_arch(arch)
def _patch_setup(self): def _patch_setup(self):
# patch setup to remove some functionnalities # patch setup to remove some functionnalities

View file

@ -21,7 +21,7 @@ class NumpyRecipe(CythonRecipe):
self.set_marker("patched") self.set_marker("patched")
def get_recipe_env(self, arch): def get_recipe_env(self, arch):
env = super(NumpyRecipe, self).get_recipe_env(arch) env = super().get_recipe_env(arch)
# CC must have the CFLAGS with arm arch, because numpy tries first to # CC must have the CFLAGS with arm arch, because numpy tries first to
# compile and execute an empty C to see if the compiler works. This is # compile and execute an empty C to see if the compiler works. This is
# obviously not working when crosscompiling # obviously not working when crosscompiling
@ -32,7 +32,7 @@ class NumpyRecipe(CythonRecipe):
return env return env
def build_arch(self, arch): def build_arch(self, arch):
super(NumpyRecipe, self).build_arch(arch) super().build_arch(arch)
sh.cp(sh.glob(join(self.build_dir, "build", "temp.*", "libnpy*.a")), sh.cp(sh.glob(join(self.build_dir, "build", "temp.*", "libnpy*.a")),
self.build_dir) self.build_dir)

View file

@ -16,7 +16,7 @@ class Python3Recipe(Recipe):
pbx_libraries = ["libz", "libbz2", "libsqlite3"] pbx_libraries = ["libz", "libbz2", "libsqlite3"]
def init_with_ctx(self, ctx): def init_with_ctx(self, ctx):
super(Python3Recipe, self).init_with_ctx(ctx) super().init_with_ctx(ctx)
self.set_python(self, "3.8") self.set_python(self, "3.8")
ctx.python_ver_dir = "python3.8" ctx.python_ver_dir = "python3.8"
ctx.python_prefix = join(ctx.dist_dir, "root", "python3") ctx.python_prefix = join(ctx.dist_dir, "root", "python3")

View file

@ -25,11 +25,7 @@ from contextlib import contextmanager
from datetime import datetime from datetime import datetime
from pprint import pformat from pprint import pformat
import logging import logging
from urllib.request import FancyURLopener, urlcleanup
try:
from urllib.request import FancyURLopener, urlcleanup
except ImportError:
from urllib import FancyURLopener, urlcleanup
try: try:
from pbxproj import XcodeProject from pbxproj import XcodeProject
@ -54,10 +50,6 @@ sh_logging.setLevel(logging.WARNING)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
IS_PY3 = sys.version_info[0] >= 3
IS_PY2 = sys.version_info[0] == 2
@contextmanager @contextmanager
def cd(newdir): def cd(newdir):
prevdir = getcwd() prevdir = getcwd()
@ -108,12 +100,11 @@ class ChromeDownloader(FancyURLopener):
urlretrieve = ChromeDownloader().retrieve urlretrieve = ChromeDownloader().retrieve
class JsonStore(object): class JsonStore:
"""Replacement of shelve using json, needed for support python 2 and 3. """Replacement of shelve using json, needed for support python 2 and 3.
""" """
def __init__(self, filename): def __init__(self, filename):
super(JsonStore, self).__init__()
self.filename = filename self.filename = filename
self.data = {} self.data = {}
if exists(filename): if exists(filename):
@ -151,17 +142,11 @@ class JsonStore(object):
self.sync() self.sync()
def sync(self): def sync(self):
# https://stackoverflow.com/a/14870531/185510 with open(self.filename, 'w') as fd:
if IS_PY3: json.dump(self.data, fd, ensure_ascii=False)
with open(self.filename, 'w') as fd:
json.dump(self.data, fd, ensure_ascii=False)
else:
with io.open(self.filename, 'w', encoding='utf-8') as fd:
fd.write(unicode( # noqa: F821
json.dumps(self.data, ensure_ascii=False)))
class Arch(object): class Arch:
def __init__(self, ctx): def __init__(self, ctx):
self.ctx = ctx self.ctx = ctx
self._ccsh = None self._ccsh = None
@ -277,7 +262,7 @@ class Arch64IOS(Arch):
sysroot = sh.xcrun("--sdk", "iphoneos", "--show-sdk-path").strip() sysroot = sh.xcrun("--sdk", "iphoneos", "--show-sdk-path").strip()
class Graph(object): class Graph:
# Taken from python-for-android/depsort # Taken from python-for-android/depsort
def __init__(self): def __init__(self):
# `graph`: dict that maps each package to a set of its dependencies. # `graph`: dict that maps each package to a set of its dependencies.
@ -321,7 +306,7 @@ class Graph(object):
bset.discard(result) bset.discard(result)
class Context(object): class Context:
env = environ.copy() env = environ.copy()
root_dir = None root_dir = None
cache_dir = None cache_dir = None
@ -335,7 +320,6 @@ class Context(object):
so_suffix = None # set by one of the hostpython so_suffix = None # set by one of the hostpython
def __init__(self): def __init__(self):
super(Context, self).__init__()
self.include_dirs = [] self.include_dirs = []
ok = True ok = True
@ -439,7 +423,7 @@ class Context(object):
return "IDEBuildOperationMaxNumberOfConcurrentCompileTasks={}".format(self.num_cores) return "IDEBuildOperationMaxNumberOfConcurrentCompileTasks={}".format(self.num_cores)
class Recipe(object): class Recipe:
props = { props = {
"is_alias": False, "is_alias": False,
"version": None, "version": None,
@ -462,7 +446,7 @@ class Recipe(object):
for prop, value in cls.props.items(): for prop, value in cls.props.items():
if not hasattr(cls, prop): if not hasattr(cls, prop):
setattr(cls, prop, value) setattr(cls, prop, value)
return super(Recipe, cls).__new__(cls) return super().__new__(cls)
# API available for recipes # API available for recipes
def download_file(self, url, filename, cwd=None): def download_file(self, url, filename, cwd=None):
@ -494,32 +478,11 @@ class Recipe(object):
while True: while True:
try: try:
urlretrieve(url, filename, report_hook) urlretrieve(url, filename, report_hook)
except AttributeError: except OSError:
if IS_PY2:
# This is caused by bug in python-future, causing occasional
# AttributeError: '_fileobject' object has no attribute 'readinto'
# It can be removed if the upstream fix is accepted. See also:
# * https://github.com/kivy/kivy-ios/issues/322
# * https://github.com/PythonCharmers/python-future/pull/423
import requests
logger.warning("urlretrieve failed. Falling back to request")
headers = {'User-agent': 'Mozilla/5.0 (X11; Linux x86_64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/28.0.1500.71 Safari/537.36'}
r = requests.get(url, headers=headers)
with open(filename, "wb") as fw:
fw.write(r.content)
break
else:
raise
except OSError as e:
attempts += 1 attempts += 1
if attempts >= 5: if attempts >= 5:
logger.error('Max download attempts reached: {}'.format(attempts)) logger.error('Max download attempts reached: {}'.format(attempts))
raise e raise
logger.warning('Download failed. Retrying in 1 second...') logger.warning('Download failed. Retrying in 1 second...')
time.sleep(1) time.sleep(1)
continue continue
@ -1092,7 +1055,7 @@ class CythonRecipe(PythonRecipe):
shprint(cmd, join(self.build_dir, "lib{}.a".format(self.name)), *dirs) shprint(cmd, join(self.build_dir, "lib{}.a".format(self.name)), *dirs)
def get_recipe_env(self, arch): def get_recipe_env(self, arch):
env = super(CythonRecipe, self).get_recipe_env(arch) env = super().get_recipe_env(arch)
env["KIVYIOSROOT"] = self.ctx.root_dir env["KIVYIOSROOT"] = self.ctx.root_dir
env["IOSSDKROOT"] = arch.sysroot env["IOSSDKROOT"] = arch.sysroot
env["CUSTOMIZED_OSX_COMPILER"] = 'True' env["CUSTOMIZED_OSX_COMPILER"] = 'True'
@ -1248,7 +1211,7 @@ def update_pbxproj(filename, pbx_frameworks=None):
project.save() project.save()
class ToolchainCL(object): class ToolchainCL:
def __init__(self): def __init__(self):
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description="Tool for managing the iOS / Python toolchain", description="Tool for managing the iOS / Python toolchain",