Skip to content

Commit

Permalink
extract contextmanager mixins
Browse files Browse the repository at this point in the history
  • Loading branch information
jorenham committed Oct 20, 2024
1 parent 47e7464 commit 57ddf2a
Show file tree
Hide file tree
Showing 9 changed files with 104 additions and 143 deletions.
15 changes: 3 additions & 12 deletions scipy-stubs/_lib/_threadsafety.pyi
Original file line number Diff line number Diff line change
@@ -1,25 +1,16 @@
from collections.abc import Callable
from types import TracebackType
from typing_extensions import TypeVar

from scipy._typing import Untyped
from scipy._typing import EnterNoneMixin

__all__ = ["ReentrancyError", "ReentrancyLock", "non_reentrant"]

_FT = TypeVar("_FT", bound=Callable[..., object])

class ReentrancyError(RuntimeError): ...

class ReentrancyLock:
class ReentrancyLock(EnterNoneMixin):
def __init__(self, /, err_msg: str) -> None: ...
def __enter__(self, /) -> None: ...
def __exit__(
self,
/,
type: type[BaseException] | None,
value: BaseException | None,
traceback: TracebackType | None,
) -> None: ...
def decorate(self, /, func: _FT) -> _FT: ...

def non_reentrant(err_msg: Untyped | None = None) -> Untyped: ...
def non_reentrant(err_msg: str | None = None) -> Callable[[_FT], _FT]: ...
14 changes: 7 additions & 7 deletions scipy-stubs/_lib/_uarray/_backend.pyi
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from contextlib import _GeneratorContextManager
from collections.abc import Callable, Iterable
from types import NotImplementedType, TracebackType
from types import NotImplementedType
from typing import Final, Generic, Literal, TypeAlias, TypedDict, final, overload, type_check_only
from typing_extensions import ParamSpec, TypeVar, Unpack

from scipy._typing import EnterNoneMixin

__all__ = [
"BackendNotImplementedError",
"Dispatchable",
Expand Down Expand Up @@ -51,20 +53,18 @@ ArgumentReplacerType: TypeAlias = Callable[
tuple[tuple[object, ...], dict[str, object]],
]

###

@final
class _BackendState: ...

@final
class _SetBackendContext:
class _SetBackendContext(EnterNoneMixin):
def __init__(self, /, *args: object, **kwargs: object) -> None: ...
def __enter__(self, /) -> None: ...
def __exit__(self, /, type: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ...

@final
class _SkipBackendContext:
class _SkipBackendContext(EnterNoneMixin):
def __init__(self, /, *args: object, **kwargs: object) -> None: ...
def __enter__(self, /) -> None: ...
def __exit__(self, /, type: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ...

@final
class _Function(Generic[_Tss, _T_co]):
Expand Down
19 changes: 3 additions & 16 deletions scipy-stubs/_lib/_util.pyi
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
from multiprocessing.pool import Pool
from collections.abc import Callable, Iterable, Mapping, Sequence
from types import TracebackType
from typing import Any, Concatenate, Final, Generic, NamedTuple, TypeAlias, overload
from typing_extensions import Self, TypeVar, override
from typing_extensions import TypeVar, override

import numpy as np
import numpy.typing as npt
Expand All @@ -15,7 +14,7 @@ from numpy.exceptions import (
VisibleDeprecationWarning as VisibleDeprecationWarning,
)
from numpy.random import Generator as Generator # noqa: ICN003
from scipy._typing import RNG, Seed
from scipy._typing import RNG, EnterSelfMixin, Seed

_T = TypeVar("_T", default=object)
_T_co = TypeVar("_T_co", covariant=True, default=object)
Expand Down Expand Up @@ -49,18 +48,10 @@ class _FunctionWrapper(Generic[_T_contra, _T_co]):
def __init__(self, /, f: Callable[Concatenate[_T_contra, ...], _T_co], args: tuple[object, ...]) -> None: ...
def __call__(self, /, x: _T_contra) -> _T_co: ...

class MapWrapper:
class MapWrapper(EnterSelfMixin):
pool: int | Pool | None
def __init__(self, /, pool: int | Callable[[Callable[[_VT], _RT], Iterable[_VT]], Sequence[_RT]] = 1) -> None: ...
def __call__(self, func: Callable[[_VT], _RT], iterable: Iterable[_VT]) -> Sequence[_RT]: ...
def __enter__(self, /) -> Self: ...
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
/,
) -> None: ...
def terminate(self, /) -> None: ...
def join(self, /) -> None: ...
def close(self, /) -> None: ...
Expand All @@ -69,10 +60,6 @@ class _RichResult(dict[str, _T]):
def __getattr__(self, name: str, /) -> _T: ...
@override
def __setattr__(self, name: str, value: _T, /) -> None: ...
@override
def __delattr__(self, name: str, /) -> None: ...
@override
def __dir__(self, /) -> list[str]: ...

def float_factorial(n: int) -> float: ...
def getfullargspec_no_self(func: Callable[..., object]) -> FullArgSpec: ...
Expand Down
16 changes: 15 additions & 1 deletion scipy-stubs/_typing.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

from os import PathLike
from collections.abc import Callable, Sequence
from types import TracebackType
from typing import IO, Any, Literal, Protocol, TypeAlias, type_check_only
from typing_extensions import LiteralString, TypeVar
from typing_extensions import LiteralString, Self, TypeVar

import numpy as np
import optype as op
Expand All @@ -23,6 +24,8 @@ __all__ = [
"ByteOrder",
"Casting",
"CorrelateMode",
"EnterNoneMixin",
"EnterSelfMixin",
"FileLike",
"FileModeRW",
"FileModeRWA",
Expand All @@ -38,6 +41,17 @@ __all__ = [
"_FortranFunction",
]

# helper mixins
@type_check_only
class EnterSelfMixin:
def __enter__(self, /) -> Self: ...
def __exit__(self, /, type: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ...

@type_check_only
class EnterNoneMixin:
def __enter__(self, /) -> None: ...
def __exit__(self, /, type: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ...

# placeholders for missing annotations
Untyped: TypeAlias = object
UntypedTuple: TypeAlias = tuple[Untyped, ...]
Expand Down
9 changes: 3 additions & 6 deletions scipy-stubs/io/_fortran.pyi
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
from types import TracebackType
from typing import Any, TypedDict, final, overload, type_check_only
from typing_extensions import Self, Unpack
from typing_extensions import Unpack

import numpy as np
import numpy.typing as npt
import optype.numpy as onpt
from scipy._typing import FileLike, FileModeRW
from scipy._typing import EnterSelfMixin, FileLike, FileModeRW

__all__ = ["FortranEOFError", "FortranFile", "FortranFormattingError"]

Expand All @@ -17,10 +16,8 @@ class _DTypeKwargs(TypedDict):
class FortranEOFError(TypeError, OSError): ...
class FortranFormattingError(TypeError, OSError): ...

class FortranFile:
class FortranFile(EnterSelfMixin):
def __init__(self, /, filename: FileLike[bytes], mode: FileModeRW = "r", header_dtype: npt.DTypeLike = ...) -> None: ...
def __enter__(self, /) -> Self: ...
def __exit__(self, /, type: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ...
def close(self, /) -> None: ...
def write_record(self, /, *items: npt.ArrayLike) -> None: ...
@overload
Expand Down
15 changes: 3 additions & 12 deletions scipy-stubs/io/_netcdf.pyi
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
from collections.abc import Mapping, Sequence
from types import TracebackType
from typing import IO, Final, Generic, Literal, TypeAlias, overload
from typing_extensions import Self, TypeVar
from typing_extensions import TypeVar

import numpy as np
import numpy.typing as npt
import optype.numpy as onpt
from optype import CanIndex
from scipy._typing import FileLike, FileModeRWA
from scipy._typing import EnterSelfMixin, FileLike, FileModeRWA

__all__ = ["netcdf_file", "netcdf_variable"]

Expand Down Expand Up @@ -62,7 +61,7 @@ TYPEMAP: Final[dict[_TypeNC, _TypeSpec]] = ...
FILLMAP: Final[dict[_TypeNC, _TypeFill]]
REVERSE: Final[dict[_TypeSpec, _TypeNC]]

class netcdf_file:
class netcdf_file(EnterSelfMixin):
fp: Final[IO[bytes]]
filename: Final[str]
use_mmap: Final[bool]
Expand All @@ -81,14 +80,6 @@ class netcdf_file:
maskandscale: bool = False,
) -> None: ...
def __del__(self, /) -> None: ...
def __enter__(self, /) -> Self: ...
def __exit__(
self,
/,
type: type[BaseException] | None,
value: BaseException | None,
traceback: TracebackType | None,
) -> None: ...
def close(self, /) -> None: ...
def createDimension(self, /, name: str, length: int) -> None: ...
@overload
Expand Down
70 changes: 32 additions & 38 deletions scipy-stubs/optimize/_differentialevolution.pyi
Original file line number Diff line number Diff line change
@@ -1,40 +1,11 @@
from scipy._lib._util import MapWrapper as MapWrapper, check_random_state as check_random_state, rng_integers as rng_integers
from scipy._typing import Untyped
from scipy.optimize import OptimizeResult as OptimizeResult, minimize as minimize
from scipy.optimize._constraints import (
Bounds as Bounds,
LinearConstraint as LinearConstraint,
NonlinearConstraint as NonlinearConstraint,
new_bounds_to_old as new_bounds_to_old,
)
from scipy.sparse import issparse as issparse
from typing_extensions import Self

def differential_evolution(
func: Untyped,
bounds: Untyped,
args: Untyped = (),
strategy: str = "best1bin",
maxiter: int = 1000,
popsize: int = 15,
tol: float = 0.01,
mutation: Untyped = (0.5, 1),
recombination: float = 0.7,
seed: Untyped | None = None,
callback: Untyped | None = None,
disp: bool = False,
polish: bool = True,
init: str = "latinhypercube",
atol: int = 0,
updating: str = "immediate",
workers: int = 1,
constraints: Untyped = (),
x0: Untyped | None = None,
*,
integrality: Untyped | None = None,
vectorized: bool = False,
) -> Untyped: ...
from scipy._typing import EnterSelfMixin, Untyped
from scipy.optimize import OptimizeResult

__all__ = ["differential_evolution"]

class DifferentialEvolutionSolver:
class DifferentialEvolutionSolver(EnterSelfMixin):
mutation_func: Untyped
strategy: Untyped
callback: Untyped
Expand Down Expand Up @@ -96,9 +67,7 @@ class DifferentialEvolutionSolver:
def convergence(self) -> Untyped: ...
def converged(self) -> Untyped: ...
def solve(self) -> Untyped: ...
def __iter__(self) -> Untyped: ...
def __enter__(self) -> Untyped: ...
def __exit__(self, *args: object) -> Untyped: ...
def __iter__(self) -> Self: ...
def __next__(self) -> Untyped: ...

class _ConstraintWrapper:
Expand All @@ -110,3 +79,28 @@ class _ConstraintWrapper:
def __init__(self, constraint: Untyped, x0: Untyped) -> None: ...
def __call__(self, x: Untyped) -> Untyped: ...
def violation(self, x: Untyped) -> Untyped: ...

def differential_evolution(
func: Untyped,
bounds: Untyped,
args: Untyped = (),
strategy: str = "best1bin",
maxiter: int = 1000,
popsize: int = 15,
tol: float = 0.01,
mutation: Untyped = (0.5, 1),
recombination: float = 0.7,
seed: Untyped | None = None,
callback: Untyped | None = None,
disp: bool = False,
polish: bool = True,
init: str = "latinhypercube",
atol: int = 0,
updating: str = "immediate",
workers: int = 1,
constraints: Untyped = (),
x0: Untyped | None = None,
*,
integrality: Untyped | None = None,
vectorized: bool = False,
) -> OptimizeResult: ...
Loading

0 comments on commit 57ddf2a

Please sign in to comment.