This commit is contained in:
2025-05-22 20:25:38 +02:00
parent 09f6750c2b
commit ce03fbf12f
529 changed files with 3353 additions and 3312 deletions

View File

@@ -189,7 +189,7 @@ class Properties(Generic[_T]):
return dir(super()) + [str(k) for k in self._data.keys()]
def __add__(self, other: Properties[_F]) -> List[Union[_T, _F]]:
return list(self) + list(other) # type: ignore
return list(self) + list(other)
def __setitem__(self, key: str, obj: _T) -> None:
self._data[key] = obj
@@ -393,16 +393,16 @@ class UniqueAppender(Generic[_T]):
self.data = data
self._unique = {}
if via:
self._data_appender = getattr(data, via) # type: ignore[assignment] # noqa: E501
self._data_appender = getattr(data, via)
elif hasattr(data, "append"):
self._data_appender = cast("List[_T]", data).append # type: ignore[assignment] # noqa: E501
self._data_appender = cast("List[_T]", data).append
elif hasattr(data, "add"):
self._data_appender = cast("Set[_T]", data).add # type: ignore[assignment] # noqa: E501
self._data_appender = cast("Set[_T]", data).add
def append(self, item: _T) -> None:
id_ = id(item)
if id_ not in self._unique:
self._data_appender(item) # type: ignore[call-arg]
self._data_appender(item)
self._unique[id_] = True
def __iter__(self) -> Iterator[_T]:
@@ -532,8 +532,8 @@ class LRUCache(typing.MutableMapping[_KT, _VT]):
def get(
self, key: _KT, default: Optional[Union[_VT, _T]] = None
) -> Optional[Union[_VT, _T]]:
item = self._data.get(key, default)
if item is not default and item is not None:
item = self._data.get(key)
if item is not None:
item[2][0] = self._inc_counter()
return item[1]
else:
@@ -677,7 +677,7 @@ class ThreadLocalRegistry(ScopedRegistry[_T]):
return self.registry.value # type: ignore[no-any-return]
except AttributeError:
val = self.registry.value = self.createfunc()
return val # type: ignore[no-any-return]
return val
def has(self) -> bool:
return hasattr(self.registry, "value")

View File

@@ -69,7 +69,7 @@ def is_exit_exception(e: BaseException) -> bool:
# Issue for context: https://github.com/python-greenlet/greenlet/issues/173
class _AsyncIoGreenlet(greenlet): # type: ignore
class _AsyncIoGreenlet(greenlet):
dead: bool
def __init__(self, fn: Callable[..., Any], driver: greenlet):
@@ -147,7 +147,7 @@ def await_fallback(awaitable: Awaitable[_T]) -> _T:
"loop is already running; can't call await_fallback() here. "
"Was IO attempted in an unexpected place?"
)
return loop.run_until_complete(awaitable) # type: ignore[no-any-return] # noqa: E501
return loop.run_until_complete(awaitable)
return current.driver.switch(awaitable) # type: ignore[no-any-return]

View File

@@ -227,11 +227,11 @@ class OrderedSet(Set[_T]):
super().add(e)
def __ior__(self, other: AbstractSet[_S]) -> OrderedSet[Union[_T, _S]]:
self.update(other) # type: ignore
return self # type: ignore
self.update(other)
return self
def union(self, *other: Iterable[_S]) -> OrderedSet[Union[_T, _S]]:
result: OrderedSet[Union[_T, _S]] = self.copy() # type: ignore
result: OrderedSet[Union[_T, _S]] = self.copy()
result.update(*other)
return result

View File

@@ -12,6 +12,7 @@ from __future__ import annotations
import base64
import dataclasses
import hashlib
import inspect
import operator
import platform
@@ -119,6 +120,18 @@ else:
return gen.athrow(typ, value, traceback)
if py39:
# python stubs don't have a public type for this. not worth
# making a protocol
def md5_not_for_security() -> Any:
return hashlib.md5(usedforsecurity=False)
else:
def md5_not_for_security() -> Any:
return hashlib.md5()
if typing.TYPE_CHECKING or py38:
from importlib import metadata as importlib_metadata
else:

View File

@@ -246,7 +246,7 @@ def deprecated_params(**specs: Tuple[str, str]) -> Callable[[_F], _F]:
# latest mypy has opinions here, not sure if they implemented
# Concatenate or something
@decorator # type: ignore
@decorator
def warned(fn: _F, *args: Any, **kwargs: Any) -> _F:
for m in check_defaults:
if (defaults[m] is None and kwargs[m] is not None) or (
@@ -290,9 +290,9 @@ def deprecated_params(**specs: Tuple[str, str]) -> Callable[[_F], _F]:
for param, (version, message) in specs.items()
},
)
decorated = warned(fn) # type: ignore
decorated = warned(fn)
decorated.__doc__ = doc
return decorated # type: ignore[no-any-return]
return decorated
return decorate
@@ -334,7 +334,7 @@ def _decorate_cls_with_warning(
clsdict["__doc__"] = doc
clsdict.pop("__dict__", None)
clsdict.pop("__weakref__", None)
cls = type(cls.__name__, cls.__bases__, clsdict) # type: ignore
cls = type(cls.__name__, cls.__bases__, clsdict)
if constructor is not None:
constructor_fn = clsdict[constructor]
@@ -376,7 +376,7 @@ def _decorate_with_warning(
else:
doc_only = ""
@decorator # type: ignore
@decorator
def warned(fn: _F, *args: Any, **kwargs: Any) -> _F:
skip_warning = not enable_warnings or kwargs.pop(
"_sa_skip_warning", False
@@ -393,9 +393,9 @@ def _decorate_with_warning(
doc = inject_docstring_text(doc, docstring_header, 1)
decorated = warned(func) # type: ignore
decorated = warned(func)
decorated.__doc__ = doc
decorated._sa_warn = lambda: _warn_with_version( # type: ignore
message, version, wtype, stacklevel=3
)
return decorated # type: ignore[no-any-return]
return decorated

View File

@@ -15,7 +15,6 @@ from __future__ import annotations
import collections
import enum
from functools import update_wrapper
import hashlib
import inspect
import itertools
import operator
@@ -87,9 +86,9 @@ else:
def md5_hex(x: Any) -> str:
x = x.encode("utf-8")
m = hashlib.md5()
m = compat.md5_not_for_security()
m.update(x)
return m.hexdigest()
return cast(str, m.hexdigest())
class safe_reraise:
@@ -266,6 +265,13 @@ def decorator(target: Callable[..., Any]) -> Callable[[_Fn], _Fn]:
metadata.update(format_argspec_plus(spec, grouped=False))
metadata["name"] = fn.__name__
if inspect.iscoroutinefunction(fn):
metadata["prefix"] = "async "
metadata["target_prefix"] = "await "
else:
metadata["prefix"] = ""
metadata["target_prefix"] = ""
# look for __ positional arguments. This is a convention in
# SQLAlchemy that arguments should be passed positionally
# rather than as keyword
@@ -277,16 +283,16 @@ def decorator(target: Callable[..., Any]) -> Callable[[_Fn], _Fn]:
if "__" in repr(spec[0]):
code = (
"""\
def %(name)s%(grouped_args)s:
return %(target)s(%(fn)s, %(apply_pos)s)
%(prefix)sdef %(name)s%(grouped_args)s:
return %(target_prefix)s%(target)s(%(fn)s, %(apply_pos)s)
"""
% metadata
)
else:
code = (
"""\
def %(name)s%(grouped_args)s:
return %(target)s(%(fn)s, %(apply_kw)s)
%(prefix)sdef %(name)s%(grouped_args)s:
return %(target_prefix)s%(target)s(%(fn)s, %(apply_kw)s)
"""
% metadata
)
@@ -526,12 +532,10 @@ def get_callable_argspec(
fn.__init__, no_self=no_self, _is_init=True
)
elif hasattr(fn, "__func__"):
return compat.inspect_getfullargspec(fn.__func__) # type: ignore[attr-defined] # noqa: E501
return compat.inspect_getfullargspec(fn.__func__)
elif hasattr(fn, "__call__"):
if inspect.ismethod(fn.__call__): # type: ignore [operator]
return get_callable_argspec(
fn.__call__, no_self=no_self # type: ignore [operator]
)
if inspect.ismethod(fn.__call__):
return get_callable_argspec(fn.__call__, no_self=no_self)
else:
raise TypeError("Can't inspect callable: %s" % fn)
else:
@@ -693,6 +697,7 @@ def create_proxy_methods(
classmethods: Sequence[str] = (),
methods: Sequence[str] = (),
attributes: Sequence[str] = (),
use_intermediate_variable: Sequence[str] = (),
) -> Callable[[_T], _T]:
"""A class decorator indicating attributes should refer to a proxy
class.
@@ -1082,7 +1087,7 @@ class generic_fn_descriptor(Generic[_T_co]):
__name__: str
def __init__(self, fget: Callable[..., _T_co], doc: Optional[str] = None):
self.fget = fget # type: ignore[assignment]
self.fget = fget
self.__doc__ = doc or fget.__doc__
self.__name__ = fget.__name__
@@ -1237,12 +1242,11 @@ class HasMemoized:
__name__: str
def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
# https://github.com/python/mypy/issues/708
self.fget = fget # type: ignore
self.fget = fget
self.__doc__ = doc or fget.__doc__
self.__name__ = fget.__name__
@overload # type: ignore[override]
@overload
def __get__(self: _MA, obj: None, cls: Any) -> _MA:
...
@@ -1476,7 +1480,7 @@ def assert_arg_type(
if isinstance(argtype, tuple):
raise exc.ArgumentError(
"Argument '%s' is expected to be one of type %s, got '%s'"
% (name, " or ".join("'%s'" % a for a in argtype), type(arg)) # type: ignore # noqa: E501
% (name, " or ".join("'%s'" % a for a in argtype), type(arg))
)
else:
raise exc.ArgumentError(
@@ -1527,7 +1531,7 @@ class classproperty(property):
self.__doc__ = fget.__doc__
def __get__(self, obj: Any, cls: Optional[type] = None) -> Any:
return self.fget(cls) # type: ignore
return self.fget(cls)
class hybridproperty(Generic[_T]):

View File

@@ -8,6 +8,7 @@
from __future__ import annotations
import builtins
import re
import sys
import typing
@@ -249,6 +250,12 @@ def eval_name_only(
try:
return base_globals[name]
except KeyError as ke:
# check in builtins as well to handle `list`, `set` or `dict`, etc.
try:
return builtins.__dict__[name]
except KeyError:
pass
raise NameError(
f"Could not locate name {name} in module {module_name}"
) from ke