Skip to content

Commit

Permalink
Lots more typing
Browse files Browse the repository at this point in the history
  • Loading branch information
chadrik committed May 20, 2024
1 parent c1d368a commit 1d2418c
Show file tree
Hide file tree
Showing 23 changed files with 354 additions and 289 deletions.
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,7 @@ exclude = [
'.*/rez/vendor/.*',
'.*/rez/tests/.*',
]
disable_error_code = ["var-annotated", "import-not-found"]
disable_error_code = ["var-annotated", "import-not-found"]
check_untyped_defs = true
# allow this for now:
allow_redefinition = true
2 changes: 1 addition & 1 deletion src/rez/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def callback(sig, frame):
else:
callback = None

if callback:
if callback is not None:
signal.signal(signal.SIGUSR1, callback) # Register handler


Expand Down
7 changes: 4 additions & 3 deletions src/rez/build_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def working_dir(self) -> str:
return self.build_system.working_dir

def build(self, install_path: str | None = None, clean: bool = False,
install=False, variants: list[int] | None = None) -> int:
install: bool = False, variants: list[int] | None = None) -> int:
"""Perform the build process.
Iterates over the package's variants, resolves the environment for
Expand Down Expand Up @@ -203,7 +203,8 @@ def repo_operation(self):
except exc_type as e:
print_warning("THE FOLLOWING ERROR WAS SKIPPED:\n%s" % str(e))

def visit_variants(self, func, variants=None, **kwargs):
def visit_variants(self, func, variants: list[Variant] | None = None,
**kwargs) -> tuple[int, list[str | None]]:
"""Iterate over variants and call a function on each."""
if variants:
present_variants = range(self.package.num_variants)
Expand Down Expand Up @@ -374,7 +375,7 @@ def run_hooks(self, hook_event, **kwargs) -> None:
"%s cancelled by %s hook '%s': %s:\n%s"
% (hook_event.noun, hook_event.label, hook.name(),
e.__class__.__name__, str(e)))
except RezError:
except RezError as e:
debug_print("Error in %s hook '%s': %s:\n%s"
% (hook_event.label, hook.name(),
e.__class__.__name__, str(e)))
Expand Down
2 changes: 1 addition & 1 deletion src/rez/build_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def get_valid_build_systems(working_dir: str,

if package:
if getattr(package, "build_command", None) is not None:
buildsys_name = "custom"
buildsys_name: str | None = "custom"
else:
buildsys_name = getattr(package, "build_system", None)

Expand Down
5 changes: 3 additions & 2 deletions src/rez/cli/_util.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project

from __future__ import annotations

import os
import sys
import signal
from argparse import _SubParsersAction, ArgumentParser, SUPPRESS, \
ArgumentError
from typing import Any


# Subcommands and their behaviors.
Expand All @@ -18,7 +19,7 @@
# The '--' arg is not treated as a special case.
# * missing: Native python argparse behavior.
#
subcommands = {
subcommands: dict[str, dict[str, Any]] = {
"bind": {},
"build": {
"arg_mode": "grouped"
Expand Down
4 changes: 2 additions & 2 deletions src/rez/cli/complete.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ def command(opts, parser, extra_arg_groups=None):

# get comp info from environment variables
comp_line = os.getenv("COMP_LINE", "")
comp_point = os.getenv("COMP_POINT", "")
comp_point_str = os.getenv("COMP_POINT", "")
try:
comp_point = int(comp_point)
comp_point = int(comp_point_str)
except:
comp_point = len(comp_line)

Expand Down
41 changes: 21 additions & 20 deletions src/rez/package_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from inspect import isclass
from hashlib import sha1
from typing import Any, Callable, Dict, Iterable, Protocol, TYPE_CHECKING
from typing import Any, Callable, Dict, Iterable, List, Protocol, TYPE_CHECKING

from rez.config import config
from rez.utils.data_utils import cached_class_property
Expand Down Expand Up @@ -635,7 +635,7 @@ def from_pod(cls, data):
)


class PackageOrderList(list):
class PackageOrderList(List[PackageOrder]):
"""A list of package orderer.
"""

Expand Down Expand Up @@ -678,29 +678,30 @@ def refresh(self) -> None:
continue
self.by_package[package] = orderer

def append(self, *args, **kwargs):
self.dirty = True
return super().append(*args, **kwargs)
if not TYPE_CHECKING:
def append(self, *args, **kwargs):
self.dirty = True
return super().append(*args, **kwargs)

def extend(self, *args, **kwargs):
self.dirty = True
return super().extend(*args, **kwargs)
def extend(self, *args, **kwargs):
self.dirty = True
return super().extend(*args, **kwargs)

def pop(self, *args, **kwargs):
self.dirty = True
return super().pop(*args, **kwargs)
def pop(self, *args, **kwargs):
self.dirty = True
return super().pop(*args, **kwargs)

def remove(self, *args, **kwargs):
self.dirty = True
return super().remove(*args, **kwargs)
def remove(self, *args, **kwargs):
self.dirty = True
return super().remove(*args, **kwargs)

def clear(self, *args, **kwargs):
self.dirty = True
return super().clear(*args, **kwargs)
def clear(self, *args, **kwargs):
self.dirty = True
return super().clear(*args, **kwargs)

def insert(self, *args, **kwargs):
self.dirty = True
return super().insert(*args, **kwargs)
def insert(self, *args, **kwargs):
self.dirty = True
return super().insert(*args, **kwargs)

def get(self, key: str, default: PackageOrder | None = None) -> PackageOrder | None:
"""
Expand Down
9 changes: 4 additions & 5 deletions src/rez/package_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ def make_resource_handle(self, resource_key, **variables) -> ResourceHandle:
variables = resource_cls.normalize_variables(variables)
return ResourceHandle(resource_key, variables)

def get_resource(self, resource_key, **variables) -> PackageRepositoryResource:
def get_resource(self, resource_key, **variables) -> Resource:
"""Get a resource.
Attempts to get and return a cached version of the resource if
Expand All @@ -469,8 +469,7 @@ def get_resource(self, resource_key, **variables) -> PackageRepositoryResource:
return self.get_resource_from_handle(handle, verify_repo=False)

def get_resource_from_handle(self, resource_handle: ResourceHandle,
verify_repo: bool = True
) -> PackageRepositoryResource:
verify_repo: bool = True) -> Resource:
"""Get a resource.
Args:
Expand Down Expand Up @@ -608,7 +607,7 @@ def are_same(self, path_1, path_2) -> bool:
return (repo_1.uid == repo_2.uid)

def get_resource(self, resource_key: str, repository_type: str,
location: str, **variables) -> PackageRepositoryResource:
location: str, **variables) -> Resource:
"""Get a resource.
Attempts to get and return a cached version of the resource if
Expand All @@ -630,7 +629,7 @@ def get_resource(self, resource_key: str, repository_type: str,
return resource

def get_resource_from_handle(self, resource_handle: ResourceHandle
) -> PackageRepositoryResource:
) -> Resource:
"""Get a resource.
Args:
Expand Down
19 changes: 16 additions & 3 deletions src/rez/package_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from abc import abstractmethod
from hashlib import sha1
from typing import Any, Iterable, Iterator, TYPE_CHECKING
from types import FunctionType, MethodType

if TYPE_CHECKING:
from rez.packages import Package, Variant
Expand Down Expand Up @@ -359,7 +360,7 @@ def parent(self) -> PackageRepositoryResource:
raise NotImplementedError

@property
def index(self):
def index(self) -> int | None:
return self.get("index", None)

@cached_property
Expand Down Expand Up @@ -394,7 +395,19 @@ def _subpath(self, ignore_shortlinks=False):
class PackageResourceHelper(PackageResource):
"""PackageResource with some common functionality included.
"""
variant_key = None
variant_key: str

if TYPE_CHECKING:
# I think these attributes are provided dynamically be LazyAttributeMeta
_commands: list[str] | str | FunctionType | MethodType | SourceCode
_pre_commands: list[str] | str | FunctionType | MethodType | SourceCode
_post_commands: list[str] | str | FunctionType | MethodType | SourceCode
variants: list[Variant]

@property
@abstractmethod
def base(self) -> str | None:
raise NotImplementedError

@property
@abstractmethod
Expand Down Expand Up @@ -430,7 +443,7 @@ def iter_variants(self) -> Iterator[Variant]:
index=index)
yield variant

def _convert_to_rex(self, commands) -> SourceCode:
def _convert_to_rex(self, commands: list[str] | str | FunctionType | MethodType | SourceCode) -> SourceCode:
if isinstance(commands, list):
from rez.utils.backcompat import convert_old_commands

Expand Down
4 changes: 2 additions & 2 deletions src/rez/package_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def _select(value):
)

if ran_once:
def _select(key, value):
def _select_kv(key, value):
if isinstance(value, dict):
value = value.get("on_variants")
else:
Expand All @@ -184,7 +184,7 @@ def _select(key, value):

tests_dict = dict(
(k, v) for k, v in tests_dict.items()
if _select(k, v)
if _select_kv(k, v)
)

return sorted(tests_dict.keys())
Expand Down
2 changes: 1 addition & 1 deletion src/rez/packages.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,7 @@ def create_package(name: str, data, package_cls=None):
return maker.get_package()


def get_variant(variant_handle: ResourceHandle | dict, context=None):
def get_variant(variant_handle: ResourceHandle | dict, context=None) -> Variant:
"""Create a variant given its handle (or serialized dict equivalent)
Args:
Expand Down

0 comments on commit 1d2418c

Please sign in to comment.