Skip to content

Commit

Permalink
chore: use from __future__ import annotations
Browse files Browse the repository at this point in the history
  • Loading branch information
mayeut committed Jul 18, 2022
1 parent 5b60cc8 commit bab6f06
Show file tree
Hide file tree
Showing 71 changed files with 285 additions and 166 deletions.
3 changes: 3 additions & 0 deletions .pre-commit-config.yaml
Expand Up @@ -18,6 +18,7 @@ repos:
hooks:
- id: pyupgrade
args: ["--py37-plus"]
exclude: ^cibuildwheel/resources/.*py$

# Autoremoves unused imports
- repo: https://github.com/hadialqattan/pycln
Expand All @@ -31,6 +32,8 @@ repos:
rev: 5.10.1
hooks:
- id: isort
args: ["-a", "from __future__ import annotations"]
exclude: ^cibuildwheel/resources/.*py$

- repo: https://github.com/psf/black
rev: 22.6.0
Expand Down
2 changes: 2 additions & 0 deletions bin/run_tests.py
@@ -1,5 +1,7 @@
#!/usr/bin/env python3

from __future__ import annotations

import argparse
import os
import subprocess
Expand Down
2 changes: 2 additions & 0 deletions bin/update_dependencies.py
@@ -1,5 +1,7 @@
#!/usr/bin/env python3

from __future__ import annotations

import os
import shutil
import subprocess
Expand Down
2 changes: 2 additions & 0 deletions bin/update_readme_changelog.py
@@ -1,5 +1,7 @@
#!/usr/bin/env python3

from __future__ import annotations

import re
import sys
from pathlib import Path
Expand Down
2 changes: 2 additions & 0 deletions cibuildwheel/__init__.py
@@ -1 +1,3 @@
from __future__ import annotations

__version__ = "2.8.0"
21 changes: 11 additions & 10 deletions cibuildwheel/__main__.py
@@ -1,3 +1,5 @@
from __future__ import annotations

import argparse
import os
import shutil
Expand All @@ -7,7 +9,6 @@
import textwrap
from pathlib import Path
from tempfile import mkdtemp
from typing import List, Set, Union

import cibuildwheel
import cibuildwheel.linux
Expand Down Expand Up @@ -257,7 +258,7 @@ def build_in_directory(args: CommandLineArguments) -> None:
log.warning(f"Can't delete temporary folder '{str(tmp_path)}'")


def print_preamble(platform: str, options: Options, identifiers: List[str]) -> None:
def print_preamble(platform: str, options: Options, identifiers: list[str]) -> None:
print(
textwrap.dedent(
"""
Expand Down Expand Up @@ -287,13 +288,13 @@ def print_preamble(platform: str, options: Options, identifiers: List[str]) -> N


def get_build_identifiers(
platform: PlatformName, build_selector: BuildSelector, architectures: Set[Architecture]
) -> List[str]:
python_configurations: Union[
List[cibuildwheel.linux.PythonConfiguration],
List[cibuildwheel.windows.PythonConfiguration],
List[cibuildwheel.macos.PythonConfiguration],
]
platform: PlatformName, build_selector: BuildSelector, architectures: set[Architecture]
) -> list[str]:
python_configurations: (
list[cibuildwheel.linux.PythonConfiguration]
| list[cibuildwheel.windows.PythonConfiguration]
| list[cibuildwheel.macos.PythonConfiguration]
)

if platform == "linux":
python_configurations = cibuildwheel.linux.get_python_configurations(
Expand All @@ -313,7 +314,7 @@ def get_build_identifiers(
return [config.identifier for config in python_configurations]


def detect_warnings(*, options: Options, identifiers: List[str]) -> List[str]:
def detect_warnings(*, options: Options, identifiers: list[str]) -> list[str]:
warnings = []

# warn about deprecated {python} and {pip}
Expand Down
15 changes: 8 additions & 7 deletions cibuildwheel/architecture.py
@@ -1,8 +1,9 @@
from __future__ import annotations

import functools
import platform as platform_module
import re
from enum import Enum
from typing import Set

from .typing import Final, Literal, PlatformName, assert_never

Expand Down Expand Up @@ -32,11 +33,11 @@ class Architecture(Enum):
ARM64 = "ARM64"

# Allow this to be sorted
def __lt__(self, other: "Architecture") -> bool:
def __lt__(self, other: Architecture) -> bool:
return self.value < other.value

@staticmethod
def parse_config(config: str, platform: PlatformName) -> "Set[Architecture]":
def parse_config(config: str, platform: PlatformName) -> set[Architecture]:
result = set()
for arch_str in re.split(r"[\s,]+", config):
if arch_str == "auto":
Expand All @@ -54,7 +55,7 @@ def parse_config(config: str, platform: PlatformName) -> "Set[Architecture]":
return result

@staticmethod
def auto_archs(platform: PlatformName) -> "Set[Architecture]":
def auto_archs(platform: PlatformName) -> set[Architecture]:
native_architecture = Architecture(platform_module.machine())
result = {native_architecture}

Expand All @@ -72,7 +73,7 @@ def auto_archs(platform: PlatformName) -> "Set[Architecture]":
return result

@staticmethod
def all_archs(platform: PlatformName) -> "Set[Architecture]":
def all_archs(platform: PlatformName) -> set[Architecture]:
all_archs_map = {
"linux": {
Architecture.x86_64,
Expand All @@ -87,7 +88,7 @@ def all_archs(platform: PlatformName) -> "Set[Architecture]":
return all_archs_map[platform]

@staticmethod
def bitness_archs(platform: PlatformName, bitness: Literal["64", "32"]) -> "Set[Architecture]":
def bitness_archs(platform: PlatformName, bitness: Literal["64", "32"]) -> set[Architecture]:
archs_32 = {Architecture.i686, Architecture.x86}
auto_archs = Architecture.auto_archs(platform)

Expand All @@ -101,7 +102,7 @@ def bitness_archs(platform: PlatformName, bitness: Literal["64", "32"]) -> "Set[

def allowed_architectures_check(
platform: PlatformName,
architectures: Set[Architecture],
architectures: set[Architecture],
) -> None:

allowed_architectures = Architecture.all_archs(platform)
Expand Down
12 changes: 7 additions & 5 deletions cibuildwheel/bashlex_eval.py
@@ -1,26 +1,28 @@
from __future__ import annotations

import subprocess
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional, Sequence
from typing import Callable, Dict, List, Sequence

import bashlex

# a function that takes a command and the environment, and returns the result
EnvironmentExecutor = Callable[[List[str], Dict[str, str]], str]


def local_environment_executor(command: List[str], env: Dict[str, str]) -> str:
def local_environment_executor(command: list[str], env: dict[str, str]) -> str:
return subprocess.run(command, env=env, text=True, stdout=subprocess.PIPE, check=True).stdout


@dataclass(frozen=True)
class NodeExecutionContext:
environment: Dict[str, str]
environment: dict[str, str]
input: str
executor: EnvironmentExecutor


def evaluate(
value: str, environment: Dict[str, str], executor: Optional[EnvironmentExecutor] = None
value: str, environment: dict[str, str], executor: EnvironmentExecutor | None = None
) -> str:
if not value:
# empty string evaluates to empty string
Expand Down Expand Up @@ -101,7 +103,7 @@ def evaluate_nodes_as_compound_command(


def evaluate_nodes_as_simple_command(
nodes: List[bashlex.ast.node], context: NodeExecutionContext
nodes: list[bashlex.ast.node], context: NodeExecutionContext
) -> str:
command = [evaluate_node(part, context=context) for part in nodes]
return context.executor(command, context.environment)
Expand Down
20 changes: 11 additions & 9 deletions cibuildwheel/environment.py
@@ -1,5 +1,7 @@
from __future__ import annotations

import dataclasses
from typing import Any, Dict, List, Mapping, Optional, Sequence
from typing import Any, Mapping, Sequence

import bashlex

Expand All @@ -12,7 +14,7 @@ class EnvironmentParseError(Exception):
pass


def split_env_items(env_string: str) -> List[str]:
def split_env_items(env_string: str) -> list[str]:
"""Splits space-separated variable assignments into a list of individual assignments.
>>> split_env_items('VAR=abc')
Expand Down Expand Up @@ -47,8 +49,8 @@ class EnvironmentAssignment(Protocol):
def evaluated_value(
self,
*,
environment: Dict[str, str],
executor: Optional[bashlex_eval.EnvironmentExecutor] = None,
environment: dict[str, str],
executor: bashlex_eval.EnvironmentExecutor | None = None,
) -> str:
"""Returns the value of this assignment, as evaluated in the environment"""

Expand Down Expand Up @@ -84,8 +86,8 @@ def __init__(self, assignment: str):

def evaluated_value(
self,
environment: Dict[str, str],
executor: Optional[bashlex_eval.EnvironmentExecutor] = None,
environment: dict[str, str],
executor: bashlex_eval.EnvironmentExecutor | None = None,
) -> str:
return bashlex_eval.evaluate(self.value, environment=environment, executor=executor)

Expand All @@ -100,16 +102,16 @@ def __eq__(self, other: object) -> bool:

@dataclasses.dataclass
class ParsedEnvironment:
assignments: List[EnvironmentAssignment]
assignments: list[EnvironmentAssignment]

def __init__(self, assignments: Sequence[EnvironmentAssignment]) -> None:
self.assignments = list(assignments)

def as_dictionary(
self,
prev_environment: Mapping[str, str],
executor: Optional[bashlex_eval.EnvironmentExecutor] = None,
) -> Dict[str, str]:
executor: bashlex_eval.EnvironmentExecutor | None = None,
) -> dict[str, str]:
environment = dict(**prev_environment)

for assignment in self.assignments:
Expand Down
5 changes: 3 additions & 2 deletions cibuildwheel/extra.py
Expand Up @@ -2,8 +2,9 @@
These are utilities for the `/bin` scripts, not for the `cibuildwheel` program.
"""

from __future__ import annotations

from io import StringIO
from typing import Dict, List

from .typing import Protocol

Expand All @@ -15,7 +16,7 @@ def __str__(self) -> str:
...


def dump_python_configurations(inp: Dict[str, Dict[str, List[Dict[str, Printable]]]]) -> str:
def dump_python_configurations(inp: dict[str, dict[str, list[dict[str, Printable]]]]) -> str:
output = StringIO()
for header, values in inp.items():
output.write(f"[{header}]\n")
Expand Down
14 changes: 8 additions & 6 deletions cibuildwheel/functools_cached_property_38.py
@@ -1,5 +1,7 @@
from __future__ import annotations

from threading import RLock
from typing import Any, Callable, Generic, Optional, Type, TypeVar, overload
from typing import Any, Callable, Generic, TypeVar, overload

__all__ = ["cached_property"]

Expand All @@ -11,11 +13,11 @@
class cached_property(Generic[_T]):
def __init__(self, func: Callable[[Any], _T]):
self.func = func
self.attrname: Optional[str] = None
self.attrname: str | None = None
self.__doc__ = func.__doc__
self.lock = RLock()

def __set_name__(self, owner: Type[Any], name: str) -> None:
def __set_name__(self, owner: type[Any], name: str) -> None:
if self.attrname is None:
self.attrname = name
elif name != self.attrname:
Expand All @@ -25,14 +27,14 @@ def __set_name__(self, owner: Type[Any], name: str) -> None:
)

@overload
def __get__(self, instance: None, owner: Optional[Type[Any]] = ...) -> "cached_property[_T]":
def __get__(self, instance: None, owner: type[Any] | None = ...) -> cached_property[_T]:
...

@overload
def __get__(self, instance: object, owner: Optional[Type[Any]] = ...) -> _T:
def __get__(self, instance: object, owner: type[Any] | None = ...) -> _T:
...

def __get__(self, instance: Optional[object], owner: Optional[Type[Any]] = None) -> Any:
def __get__(self, instance: object | None, owner: type[Any] | None = None) -> Any:
if instance is None:
return self
if self.attrname is None:
Expand Down
20 changes: 11 additions & 9 deletions cibuildwheel/linux.py
@@ -1,9 +1,11 @@
from __future__ import annotations

import subprocess
import sys
import textwrap
from dataclasses import dataclass
from pathlib import Path, PurePath, PurePosixPath
from typing import Iterator, List, Set, Tuple
from typing import Iterator, Tuple

from .architecture import Architecture
from .logger import log
Expand Down Expand Up @@ -35,15 +37,15 @@ def path(self) -> PurePosixPath:

@dataclass(frozen=True)
class BuildStep:
platform_configs: List[PythonConfiguration]
platform_configs: list[PythonConfiguration]
platform_tag: str
container_image: str


def get_python_configurations(
build_selector: BuildSelector,
architectures: Set[Architecture],
) -> List[PythonConfiguration]:
architectures: set[Architecture],
) -> list[PythonConfiguration]:

full_python_configs = read_python_configs("linux")

Expand Down Expand Up @@ -79,7 +81,7 @@ def container_image_for_python_configuration(config: PythonConfiguration, option


def get_build_steps(
options: Options, python_configurations: List[PythonConfiguration]
options: Options, python_configurations: list[PythonConfiguration]
) -> Iterator[BuildStep]:
"""
Groups PythonConfigurations into BuildSteps. Each BuildStep represents a
Expand Down Expand Up @@ -110,7 +112,7 @@ def get_build_steps(
def build_in_container(
*,
options: Options,
platform_configs: List[PythonConfiguration],
platform_configs: list[PythonConfiguration],
container: OCIContainer,
container_project_path: PurePath,
container_package_dir: PurePath,
Expand Down Expand Up @@ -140,13 +142,13 @@ def build_in_container(
)
container.call(["sh", "-c", before_all_prepared], env=env)

built_wheels: List[PurePosixPath] = []
built_wheels: list[PurePosixPath] = []

for config in platform_configs:
log.build_start(config.identifier)
build_options = options.build_options(config.identifier)

dependency_constraint_flags: List[PathOrStr] = []
dependency_constraint_flags: list[PathOrStr] = []

if build_options.dependency_constraints:
constraints_file = build_options.dependency_constraints.get_for_python_version(
Expand Down Expand Up @@ -395,7 +397,7 @@ def build(options: Options, tmp_path: Path) -> None: # pylint: disable=unused-a
sys.exit(1)


def _matches_prepared_command(error_cmd: List[str], command_template: str) -> bool:
def _matches_prepared_command(error_cmd: list[str], command_template: str) -> bool:
if len(error_cmd) < 3 or error_cmd[0:2] != ["sh", "-c"]:
return False
command_prefix = command_template.split("{", maxsplit=1)[0].strip()
Expand Down

0 comments on commit bab6f06

Please sign in to comment.