]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
pep-484 for sqlalchemy.event; use future annotations
authorMike Bayer <mike_mp@zzzcomputing.com>
Sun, 13 Feb 2022 21:45:18 +0000 (16:45 -0500)
committerMike Bayer <mike_mp@zzzcomputing.com>
Tue, 15 Feb 2022 22:10:33 +0000 (17:10 -0500)
__future__.annotations mode allows us to use non-string
annotations for argument and return types in most cases,
but more importantly it removes a large amount of runtime
overhead that would be spent in evaluating the annotations.

Change-Id: I2f5b6126fe0019713fc50001be3627b664019ede
References: #6810

129 files changed:
.pre-commit-config.yaml
lib/sqlalchemy/__init__.py
lib/sqlalchemy/engine/_py_processors.py
lib/sqlalchemy/engine/_py_row.py
lib/sqlalchemy/engine/_py_util.py
lib/sqlalchemy/engine/base.py
lib/sqlalchemy/engine/characteristics.py
lib/sqlalchemy/engine/create.py
lib/sqlalchemy/engine/cursor.py
lib/sqlalchemy/engine/default.py
lib/sqlalchemy/engine/events.py
lib/sqlalchemy/engine/interfaces.py
lib/sqlalchemy/engine/mock.py
lib/sqlalchemy/engine/processors.py
lib/sqlalchemy/engine/reflection.py
lib/sqlalchemy/engine/result.py
lib/sqlalchemy/engine/row.py
lib/sqlalchemy/engine/strategies.py
lib/sqlalchemy/engine/url.py
lib/sqlalchemy/engine/util.py
lib/sqlalchemy/event/__init__.py
lib/sqlalchemy/event/api.py
lib/sqlalchemy/event/attr.py
lib/sqlalchemy/event/base.py
lib/sqlalchemy/event/legacy.py
lib/sqlalchemy/event/registry.py
lib/sqlalchemy/events.py
lib/sqlalchemy/exc.py
lib/sqlalchemy/ext/mypy/apply.py
lib/sqlalchemy/ext/mypy/decl_class.py
lib/sqlalchemy/ext/mypy/infer.py
lib/sqlalchemy/ext/mypy/names.py
lib/sqlalchemy/ext/mypy/plugin.py
lib/sqlalchemy/ext/mypy/util.py
lib/sqlalchemy/ext/orderinglist.py
lib/sqlalchemy/inspection.py
lib/sqlalchemy/log.py
lib/sqlalchemy/orm/__init__.py
lib/sqlalchemy/orm/_orm_constructors.py
lib/sqlalchemy/orm/attributes.py
lib/sqlalchemy/orm/base.py
lib/sqlalchemy/orm/clsregistry.py
lib/sqlalchemy/orm/collections.py
lib/sqlalchemy/orm/context.py
lib/sqlalchemy/orm/decl_api.py
lib/sqlalchemy/orm/dependency.py
lib/sqlalchemy/orm/descriptor_props.py
lib/sqlalchemy/orm/dynamic.py
lib/sqlalchemy/orm/evaluator.py
lib/sqlalchemy/orm/events.py
lib/sqlalchemy/orm/exc.py
lib/sqlalchemy/orm/identity.py
lib/sqlalchemy/orm/instrumentation.py
lib/sqlalchemy/orm/interfaces.py
lib/sqlalchemy/orm/loading.py
lib/sqlalchemy/orm/mapped_collection.py
lib/sqlalchemy/orm/mapper.py
lib/sqlalchemy/orm/path_registry.py
lib/sqlalchemy/orm/persistence.py
lib/sqlalchemy/orm/properties.py
lib/sqlalchemy/orm/query.py
lib/sqlalchemy/orm/scoping.py
lib/sqlalchemy/orm/session.py
lib/sqlalchemy/orm/state.py
lib/sqlalchemy/orm/state_changes.py
lib/sqlalchemy/orm/strategies.py
lib/sqlalchemy/orm/strategy_options.py
lib/sqlalchemy/orm/sync.py
lib/sqlalchemy/orm/unitofwork.py
lib/sqlalchemy/orm/util.py
lib/sqlalchemy/pool/base.py
lib/sqlalchemy/schema.py
lib/sqlalchemy/sql/_dml_constructors.py
lib/sqlalchemy/sql/_elements_constructors.py
lib/sqlalchemy/sql/_py_util.py
lib/sqlalchemy/sql/_selectable_constructors.py
lib/sqlalchemy/sql/_typing.py
lib/sqlalchemy/sql/annotation.py
lib/sqlalchemy/sql/base.py
lib/sqlalchemy/sql/cache_key.py
lib/sqlalchemy/sql/coercions.py
lib/sqlalchemy/sql/compiler.py
lib/sqlalchemy/sql/crud.py
lib/sqlalchemy/sql/ddl.py
lib/sqlalchemy/sql/default_comparator.py
lib/sqlalchemy/sql/dml.py
lib/sqlalchemy/sql/elements.py
lib/sqlalchemy/sql/events.py
lib/sqlalchemy/sql/expression.py
lib/sqlalchemy/sql/functions.py
lib/sqlalchemy/sql/lambdas.py
lib/sqlalchemy/sql/naming.py
lib/sqlalchemy/sql/operators.py
lib/sqlalchemy/sql/roles.py
lib/sqlalchemy/sql/schema.py
lib/sqlalchemy/sql/selectable.py
lib/sqlalchemy/sql/sqltypes.py
lib/sqlalchemy/sql/traversals.py
lib/sqlalchemy/sql/type_api.py
lib/sqlalchemy/sql/util.py
lib/sqlalchemy/sql/visitors.py
lib/sqlalchemy/testing/assertions.py
lib/sqlalchemy/testing/assertsql.py
lib/sqlalchemy/testing/asyncio.py
lib/sqlalchemy/testing/config.py
lib/sqlalchemy/testing/engines.py
lib/sqlalchemy/testing/entities.py
lib/sqlalchemy/testing/fixtures.py
lib/sqlalchemy/testing/pickleable.py
lib/sqlalchemy/testing/profiling.py
lib/sqlalchemy/testing/provision.py
lib/sqlalchemy/testing/requirements.py
lib/sqlalchemy/testing/schema.py
lib/sqlalchemy/testing/util.py
lib/sqlalchemy/testing/warnings.py
lib/sqlalchemy/types.py
lib/sqlalchemy/util/_collections.py
lib/sqlalchemy/util/_concurrency_py3k.py
lib/sqlalchemy/util/_preloaded.py
lib/sqlalchemy/util/_py_collections.py
lib/sqlalchemy/util/compat.py
lib/sqlalchemy/util/concurrency.py
lib/sqlalchemy/util/deprecations.py
lib/sqlalchemy/util/langhelpers.py
lib/sqlalchemy/util/topological.py
lib/sqlalchemy/util/typing.py
pyproject.toml
setup.cfg
tox.ini

index 06939146842ca350b764ac3a7b4bcdc25261fc45..b888441fd470d6183cdf218aacba9d1cf43ab924 100644 (file)
@@ -18,6 +18,7 @@ repos:
         additional_dependencies:
           - flake8-import-order
           - flake8-builtins
+          - flake8-future-annotations
           - flake8-docstrings>=1.6.0
           - flake8-rst-docstrings
           # flake8-rst-docstrings dependency, leaving it here
index eadb427d0d42f73568016ca554048cf063728efe..dc1c536c8df59b4b181cb0171b76b99468b0f576 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from . import util as _util
 from .engine import AdaptedConnection as AdaptedConnection
 from .engine import BaseCursorResult as BaseCursorResult
index 66c915a8fb83648eaed64164d7e8c7eeac49d585..e3024471a22351bd3736203c3290d91539f31c84 100644 (file)
@@ -13,6 +13,8 @@ They all share one common characteristic: None is passed through unchanged.
 
 """
 
+from __future__ import annotations
+
 import datetime
 import re
 
index 981b6e0b2772ed8304cb2274ad7d75a9846b442a..a6d5b79d59cbcaaf0ed78988b753b115f3cd9e2d 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
 import operator
 
 MD_INDEX = 0  # integer index in cursor.description
index 2db6c049bb32f9fc50cb5ad9b28f445ddc2dbee3..ff03a47613cc92ccdfb3fb9b65bbbb18359b7cf0 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
 from collections import abc as collections_abc
 
 from .. import exc
index 4045eae907e7fc1b1416d4b2b9e2c2df7ee2a1a6..4fd273948468e78521e278fd481b7d33684d8999 100644 (file)
@@ -4,6 +4,8 @@
 #
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
+from __future__ import annotations
+
 import contextlib
 import sys
 import typing
index 10455451fdc667bbb3f777dfc18d88f607b9e167..c3674c931e95c6f6b6f65915f711527aa9682d61 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
 import abc
 
 
index 2f8ce17df92dacc5c0f511472607eaace1a08a0c..a252b7cfebfea0ebf181da56c155844588125012 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from typing import Any
 from typing import Union
 
index f372b88985dc7c98ceb5a5dac2d3de5f5111e538..2b077056fa59935d599d14ea464c17fa6ace8abf 100644 (file)
@@ -9,6 +9,8 @@
 :class:`.BaseCursorResult`, :class:`.CursorResult`."""
 
 
+from __future__ import annotations
+
 import collections
 import functools
 
index 4861214c4afc58df5025532dd3d5eede4bab7fc0..b7dbfc52ee34c96d935399a77b1ca847f6e0c22d 100644 (file)
@@ -13,6 +13,8 @@ as the base class for their own corresponding classes.
 
 """
 
+from __future__ import annotations
+
 import functools
 import random
 import re
index 3af46c119b8acabd9523e18646071263f392c17f..ab462bbe1fa23fbc48ea4fc38a2ef6ac3618e33b 100644 (file)
@@ -6,6 +6,8 @@
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
 
+from __future__ import annotations
+
 from .base import Engine
 from .interfaces import ConnectionEventsTarget
 from .interfaces import Dialect
index 2bbe23e0425f269ff7e24e8f6c5d0173ea142d39..ce884614c0678ed0ed2f6a7f7266c5307b270d39 100644 (file)
@@ -7,6 +7,8 @@
 
 """Define core interfaces used by the engine system."""
 
+from __future__ import annotations
+
 from enum import Enum
 from typing import Any
 from typing import Callable
index cee4db80263287772c4cfcceb7802ed44366c7ca..76e77a3f3dcc56e7067575286070ffa74937d28f 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from operator import attrgetter
 
 from . import url as _url
index 829af679632c3c4d4e1c25d107f6fe2aa2dc3139..398c1fa36153381e13afd18ff9e9e45762b3f383 100644 (file)
@@ -12,6 +12,8 @@ processors.
 They all share one common characteristic: None is passed through unchanged.
 
 """
+from __future__ import annotations
+
 from ._py_processors import str_to_datetime_processor_factory  # noqa
 
 try:
index 882392e9c212585e1e8feb57c435512126d28318..e1281365e9c196115a9be7bb15bc9c5226d88239 100644 (file)
@@ -24,6 +24,8 @@ methods such as get_table_names, get_columns, etc.
    use the key 'name'. So for most return values, each record will have a
    'name' attribute..
 """
+from __future__ import annotations
+
 import contextlib
 from typing import List
 from typing import Optional
index 5970e2448fac73a3b8d79104c8f6aa7c5c3f182e..2e54c87dbd507e27f6b424a6cbbb38f2d29e2345 100644 (file)
@@ -6,6 +6,9 @@
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
 """Define generic result set constructs."""
+
+from __future__ import annotations
+
 import collections.abc as collections_abc
 import functools
 import itertools
index 75c56450e2b7846c612d64e71d2e4d7cf99aa984..29b2f338b6ee228df2c550eb4c0257d8e485a9d9 100644 (file)
@@ -7,6 +7,8 @@
 
 """Define row constructs including :class:`.Row`."""
 
+from __future__ import annotations
+
 import collections.abc as collections_abc
 import operator
 import typing
index 8042acd39a21dcd9e34d136aaa7035430a6725fa..7f291af823b54b0887ed0108eeffe1e4010ee473 100644 (file)
@@ -10,6 +10,8 @@
 
 """
 
+from __future__ import annotations
+
 from .mock import MockConnection  # noqa
 
 
index ec5ab2bec717993d3c8b078a071393f08578bf5f..a55233397e3bac26c2811e7834e97cabda0cdcb4 100644 (file)
@@ -14,6 +14,8 @@ argument; alternatively, the URL is a public-facing construct which can
 be used directly and is also accepted directly by ``create_engine()``.
 """
 
+from __future__ import annotations
+
 import collections.abc as collections_abc
 import re
 from typing import Dict
index f74cd3f8471ea9f00e46aed08ff3a976b7bc461d..f9ee65befea77dbabf893b32082fae80abf6b180 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from .. import exc
 from .. import util
 
index a89bea894e2e8d8a6864a6d673f00ee664dcfe1d..2d10372ab11c26cb74e3dd912c38efe0237384ad 100644 (file)
@@ -5,13 +5,15 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
-from .api import CANCEL
-from .api import contains
-from .api import listen
-from .api import listens_for
-from .api import NO_RETVAL
-from .api import remove
-from .attr import RefCollection
-from .base import dispatcher
-from .base import Events
+from __future__ import annotations
+
+from .api import CANCEL as CANCEL
+from .api import contains as contains
+from .api import listen as listen
+from .api import listens_for as listens_for
+from .api import NO_RETVAL as NO_RETVAL
+from .api import remove as remove
+from .attr import RefCollection as RefCollection
+from .base import dispatcher as dispatcher
+from .base import Events as Events
 from .legacy import _legacy_signature
index d2fd9473cc5571ad89b2ede0dbc7aaf5cf99d492..52f796b19df2e16c72dd9333aae25814a4edce8f 100644 (file)
@@ -8,8 +8,15 @@
 """Public API functions for the event system.
 
 """
+from __future__ import annotations
+
+from typing import Any
+from typing import Callable
+
 from .base import _registrars
+from .registry import _ET
 from .registry import _EventKey
+from .registry import _ListenerFnType
 from .. import exc
 from .. import util
 
@@ -18,7 +25,9 @@ CANCEL = util.symbol("CANCEL")
 NO_RETVAL = util.symbol("NO_RETVAL")
 
 
-def _event_key(target, identifier, fn):
+def _event_key(
+    target: _ET, identifier: str, fn: _ListenerFnType
+) -> _EventKey[_ET]:
     for evt_cls in _registrars[identifier]:
         tgt = evt_cls._accept_with(target)
         if tgt is not None:
@@ -29,7 +38,9 @@ def _event_key(target, identifier, fn):
         )
 
 
-def listen(target, identifier, fn, *args, **kw):
+def listen(
+    target: Any, identifier: str, fn: Callable[..., Any], *args: Any, **kw: Any
+) -> None:
     """Register a listener function for the given target.
 
     The :func:`.listen` function is part of the primary interface for the
@@ -113,7 +124,9 @@ def listen(target, identifier, fn, *args, **kw):
     _event_key(target, identifier, fn).listen(*args, **kw)
 
 
-def listens_for(target, identifier, *args, **kw):
+def listens_for(
+    target: Any, identifier: str, *args: Any, **kw: Any
+) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
     """Decorate a function as a listener for the given target + identifier.
 
     The :func:`.listens_for` decorator is part of the primary interface for the
@@ -154,14 +167,14 @@ def listens_for(target, identifier, *args, **kw):
 
     """
 
-    def decorate(fn):
+    def decorate(fn: Callable[..., Any]) -> Callable[..., Any]:
         listen(target, identifier, fn, *args, **kw)
         return fn
 
     return decorate
 
 
-def remove(target, identifier, fn):
+def remove(target: Any, identifier: str, fn: Callable[..., Any]) -> None:
     """Remove an event listener.
 
     The arguments here should match exactly those which were sent to
@@ -211,7 +224,7 @@ def remove(target, identifier, fn):
     _event_key(target, identifier, fn).remove()
 
 
-def contains(target, identifier, fn):
+def contains(target: Any, identifier: str, fn: Callable[..., Any]) -> bool:
     """Return True if the given target/ident/fn is set up to listen."""
 
     return _event_key(target, identifier, fn).contains()
index a059662224c452ad5557edeb7941c12ca800cf0c..d1ae7a84527edcc681aff6f3de4dc380aa9b37b9 100644 (file)
@@ -28,43 +28,89 @@ as well as support for subclass propagation (e.g. events assigned to
 ``Pool`` vs. ``QueuePool``) are all implemented here.
 
 """
+from __future__ import annotations
+
 import collections
 from itertools import chain
 import threading
+from types import TracebackType
+import typing
+from typing import Any
+from typing import cast
+from typing import Collection
+from typing import Deque
+from typing import FrozenSet
+from typing import Generic
+from typing import Iterator
+from typing import MutableMapping
+from typing import MutableSequence
+from typing import NoReturn
+from typing import Optional
+from typing import Sequence
+from typing import Set
+from typing import Tuple
+from typing import Type
+from typing import TypeVar
+from typing import Union
 import weakref
 
 from . import legacy
 from . import registry
+from .registry import _ET
+from .registry import _EventKey
+from .registry import _ListenerFnType
 from .. import exc
 from .. import util
 from ..util.concurrency import AsyncAdaptedLock
+from ..util.typing import Protocol
+
+_T = TypeVar("_T", bound=Any)
+
+if typing.TYPE_CHECKING:
+    from .base import _Dispatch
+    from .base import _HasEventsDispatch
+    from .base import _JoinedDispatcher
 
 
-class RefCollection(util.MemoizedSlots):
+class RefCollection(util.MemoizedSlots, Generic[_ET]):
     __slots__ = ("ref",)
 
-    def _memoized_attr_ref(self):
+    ref: weakref.ref[RefCollection[_ET]]
+
+    def _memoized_attr_ref(self) -> weakref.ref[RefCollection[_ET]]:
         return weakref.ref(self, registry._collection_gced)
 
 
-class _empty_collection:
-    def append(self, element):
+class _empty_collection(Collection[_T]):
+    def append(self, element: _T) -> None:
+        pass
+
+    def appendleft(self, element: _T) -> None:
         pass
 
-    def extend(self, other):
+    def extend(self, other: Sequence[_T]) -> None:
         pass
 
-    def remove(self, element):
+    def remove(self, element: _T) -> None:
         pass
 
-    def __iter__(self):
+    def __contains__(self, element: Any) -> bool:
+        return False
+
+    def __iter__(self) -> Iterator[_T]:
         return iter([])
 
-    def clear(self):
+    def clear(self) -> None:
         pass
 
+    def __len__(self) -> int:
+        return 0
+
+
+_ListenerFnSequenceType = Union[Deque[_T], _empty_collection[_T]]
+
 
-class _ClsLevelDispatch(RefCollection):
+class _ClsLevelDispatch(RefCollection[_ET]):
     """Class-level events on :class:`._Dispatch` classes."""
 
     __slots__ = (
@@ -77,7 +123,20 @@ class _ClsLevelDispatch(RefCollection):
         "__weakref__",
     )
 
-    def __init__(self, parent_dispatch_cls, fn):
+    clsname: str
+    name: str
+    arg_names: Sequence[str]
+    has_kw: bool
+    legacy_signatures: MutableSequence[legacy._LegacySignatureType]
+    _clslevel: MutableMapping[
+        Type[_ET], _ListenerFnSequenceType[_ListenerFnType]
+    ]
+
+    def __init__(
+        self,
+        parent_dispatch_cls: Type[_HasEventsDispatch[_ET]],
+        fn: _ListenerFnType,
+    ):
         self.name = fn.__name__
         self.clsname = parent_dispatch_cls.__name__
         argspec = util.inspect_getfullargspec(fn)
@@ -94,7 +153,9 @@ class _ClsLevelDispatch(RefCollection):
 
         self._clslevel = weakref.WeakKeyDictionary()
 
-    def _adjust_fn_spec(self, fn, named):
+    def _adjust_fn_spec(
+        self, fn: _ListenerFnType, named: bool
+    ) -> _ListenerFnType:
         if named:
             fn = self._wrap_fn_for_kw(fn)
         if self.legacy_signatures:
@@ -106,15 +167,15 @@ class _ClsLevelDispatch(RefCollection):
                 fn = legacy._wrap_fn_for_legacy(self, fn, argspec)
         return fn
 
-    def _wrap_fn_for_kw(self, fn):
-        def wrap_kw(*args, **kw):
+    def _wrap_fn_for_kw(self, fn: _ListenerFnType) -> _ListenerFnType:
+        def wrap_kw(*args: Any, **kw: Any) -> Any:
             argdict = dict(zip(self.arg_names, args))
             argdict.update(kw)
             return fn(**argdict)
 
         return wrap_kw
 
-    def insert(self, event_key, propagate):
+    def insert(self, event_key: _EventKey[_ET], propagate: bool) -> None:
         target = event_key.dispatch_target
         assert isinstance(
             target, type
@@ -125,6 +186,7 @@ class _ClsLevelDispatch(RefCollection):
             )
 
         for cls in util.walk_subclasses(target):
+            cls = cast(Type[_ET], cls)
             if cls is not target and cls not in self._clslevel:
                 self.update_subclass(cls)
             else:
@@ -133,7 +195,7 @@ class _ClsLevelDispatch(RefCollection):
                 self._clslevel[cls].appendleft(event_key._listen_fn)
         registry._stored_in_collection(event_key, self)
 
-    def append(self, event_key, propagate):
+    def append(self, event_key: _EventKey[_ET], propagate: bool) -> None:
         target = event_key.dispatch_target
         assert isinstance(
             target, type
@@ -143,6 +205,7 @@ class _ClsLevelDispatch(RefCollection):
                 "Can't assign an event directly to the %s class" % target
             )
         for cls in util.walk_subclasses(target):
+            cls = cast("Type[_ET]", cls)
             if cls is not target and cls not in self._clslevel:
                 self.update_subclass(cls)
             else:
@@ -151,39 +214,41 @@ class _ClsLevelDispatch(RefCollection):
                 self._clslevel[cls].append(event_key._listen_fn)
         registry._stored_in_collection(event_key, self)
 
-    def _assign_cls_collection(self, target):
+    def _assign_cls_collection(self, target: Type[_ET]) -> None:
         if getattr(target, "_sa_propagate_class_events", True):
             self._clslevel[target] = collections.deque()
         else:
             self._clslevel[target] = _empty_collection()
 
-    def update_subclass(self, target):
+    def update_subclass(self, target: Type[_ET]) -> None:
         if target not in self._clslevel:
             self._assign_cls_collection(target)
         clslevel = self._clslevel[target]
         for cls in target.__mro__[1:]:
+            cls = cast("Type[_ET]", cls)
             if cls in self._clslevel:
                 clslevel.extend(
                     [fn for fn in self._clslevel[cls] if fn not in clslevel]
                 )
 
-    def remove(self, event_key):
+    def remove(self, event_key: _EventKey[_ET]) -> None:
         target = event_key.dispatch_target
         for cls in util.walk_subclasses(target):
+            cls = cast("Type[_ET]", cls)
             if cls in self._clslevel:
                 self._clslevel[cls].remove(event_key._listen_fn)
         registry._removed_from_collection(event_key, self)
 
-    def clear(self):
+    def clear(self) -> None:
         """Clear all class level listeners"""
 
-        to_clear = set()
+        to_clear: Set[_ListenerFnType] = set()
         for dispatcher in self._clslevel.values():
             to_clear.update(dispatcher)
             dispatcher.clear()
         registry._clear(self, to_clear)
 
-    def for_modify(self, obj):
+    def for_modify(self, obj: _Dispatch[_ET]) -> _ClsLevelDispatch[_ET]:
         """Return an event collection which can be modified.
 
         For _ClsLevelDispatch at the class level of
@@ -193,14 +258,30 @@ class _ClsLevelDispatch(RefCollection):
         return self
 
 
-class _InstanceLevelDispatch(RefCollection):
+class _InstanceLevelDispatch(RefCollection[_ET], Collection[_ListenerFnType]):
     __slots__ = ()
 
-    def _adjust_fn_spec(self, fn, named):
+    parent: _ClsLevelDispatch[_ET]
+
+    def _adjust_fn_spec(
+        self, fn: _ListenerFnType, named: bool
+    ) -> _ListenerFnType:
         return self.parent._adjust_fn_spec(fn, named)
 
+    def __contains__(self, item: Any) -> bool:
+        raise NotImplementedError()
+
+    def __len__(self) -> int:
+        raise NotImplementedError()
+
+    def __iter__(self) -> Iterator[_ListenerFnType]:
+        raise NotImplementedError()
+
+    def __bool__(self) -> bool:
+        raise NotImplementedError()
+
 
-class _EmptyListener(_InstanceLevelDispatch):
+class _EmptyListener(_InstanceLevelDispatch[_ET]):
     """Serves as a proxy interface to the events
     served by a _ClsLevelDispatch, when there are no
     instance-level events present.
@@ -210,19 +291,22 @@ class _EmptyListener(_InstanceLevelDispatch):
 
     """
 
-    propagate = frozenset()
-    listeners = ()
-
     __slots__ = "parent", "parent_listeners", "name"
 
-    def __init__(self, parent, target_cls):
+    propagate: FrozenSet[_ListenerFnType] = frozenset()
+    listeners: Tuple[()] = ()
+    parent: _ClsLevelDispatch[_ET]
+    parent_listeners: _ListenerFnSequenceType[_ListenerFnType]
+    name: str
+
+    def __init__(self, parent: _ClsLevelDispatch[_ET], target_cls: Type[_ET]):
         if target_cls not in parent._clslevel:
             parent.update_subclass(target_cls)
-        self.parent = parent  # _ClsLevelDispatch
+        self.parent = parent
         self.parent_listeners = parent._clslevel[target_cls]
         self.name = parent.name
 
-    def for_modify(self, obj):
+    def for_modify(self, obj: _Dispatch[_ET]) -> _ListenerCollection[_ET]:
         """Return an event collection which can be modified.
 
         For _EmptyListener at the instance level of
@@ -231,6 +315,7 @@ class _EmptyListener(_InstanceLevelDispatch):
         and returns it.
 
         """
+        assert obj._instance_cls is not None
         result = _ListenerCollection(self.parent, obj._instance_cls)
         if getattr(obj, self.name) is self:
             setattr(obj, self.name, result)
@@ -238,41 +323,79 @@ class _EmptyListener(_InstanceLevelDispatch):
             assert isinstance(getattr(obj, self.name), _JoinedListener)
         return result
 
-    def _needs_modify(self, *args, **kw):
+    def _needs_modify(self, *args: Any, **kw: Any) -> NoReturn:
         raise NotImplementedError("need to call for_modify()")
 
-    exec_once = (
-        exec_once_unless_exception
-    ) = insert = append = remove = clear = _needs_modify
+    def exec_once(self, *args: Any, **kw: Any) -> NoReturn:
+        self._needs_modify(*args, **kw)
+
+    def exec_once_unless_exception(self, *args: Any, **kw: Any) -> NoReturn:
+        self._needs_modify(*args, **kw)
+
+    def insert(self, *args: Any, **kw: Any) -> NoReturn:
+        self._needs_modify(*args, **kw)
 
-    def __call__(self, *args, **kw):
+    def append(self, *args: Any, **kw: Any) -> NoReturn:
+        self._needs_modify(*args, **kw)
+
+    def remove(self, *args: Any, **kw: Any) -> NoReturn:
+        self._needs_modify(*args, **kw)
+
+    def clear(self, *args: Any, **kw: Any) -> NoReturn:
+        self._needs_modify(*args, **kw)
+
+    def __call__(self, *args: Any, **kw: Any) -> None:
         """Execute this event."""
 
         for fn in self.parent_listeners:
             fn(*args, **kw)
 
-    def __len__(self):
+    def __contains__(self, item: Any) -> bool:
+        return item in self.parent_listeners
+
+    def __len__(self) -> int:
         return len(self.parent_listeners)
 
-    def __iter__(self):
+    def __iter__(self) -> Iterator[_ListenerFnType]:
         return iter(self.parent_listeners)
 
-    def __bool__(self):
+    def __bool__(self) -> bool:
         return bool(self.parent_listeners)
 
     __nonzero__ = __bool__
 
 
-class _CompoundListener(_InstanceLevelDispatch):
+class _MutexProtocol(Protocol):
+    def __enter__(self) -> bool:
+        ...
+
+    def __exit__(
+        self,
+        exc_type: Optional[Type[BaseException]],
+        exc_val: Optional[BaseException],
+        exc_tb: Optional[TracebackType],
+    ) -> Optional[bool]:
+        ...
+
+
+class _CompoundListener(_InstanceLevelDispatch[_ET]):
     __slots__ = "_exec_once_mutex", "_exec_once", "_exec_w_sync_once"
 
-    def _set_asyncio(self):
+    _exec_once_mutex: _MutexProtocol
+    parent_listeners: Collection[_ListenerFnType]
+    listeners: Collection[_ListenerFnType]
+    _exec_once: bool
+    _exec_w_sync_once: bool
+
+    def _set_asyncio(self) -> None:
         self._exec_once_mutex = AsyncAdaptedLock()
 
-    def _memoized_attr__exec_once_mutex(self):
+    def _memoized_attr__exec_once_mutex(self) -> _MutexProtocol:
         return threading.Lock()
 
-    def _exec_once_impl(self, retry_on_exception, *args, **kw):
+    def _exec_once_impl(
+        self, retry_on_exception: bool, *args: Any, **kw: Any
+    ) -> None:
         with self._exec_once_mutex:
             if not self._exec_once:
                 try:
@@ -285,14 +408,14 @@ class _CompoundListener(_InstanceLevelDispatch):
                     if not exception or not retry_on_exception:
                         self._exec_once = True
 
-    def exec_once(self, *args, **kw):
+    def exec_once(self, *args: Any, **kw: Any) -> None:
         """Execute this event, but only if it has not been
         executed already for this collection."""
 
         if not self._exec_once:
             self._exec_once_impl(False, *args, **kw)
 
-    def exec_once_unless_exception(self, *args, **kw):
+    def exec_once_unless_exception(self, *args: Any, **kw: Any) -> None:
         """Execute this event, but only if it has not been
         executed already for this collection, or was called
         by a previous exec_once_unless_exception call and
@@ -307,7 +430,7 @@ class _CompoundListener(_InstanceLevelDispatch):
         if not self._exec_once:
             self._exec_once_impl(True, *args, **kw)
 
-    def _exec_w_sync_on_first_run(self, *args, **kw):
+    def _exec_w_sync_on_first_run(self, *args: Any, **kw: Any) -> None:
         """Execute this event, and use a mutex if it has not been
         executed already for this collection, or was called
         by a previous _exec_w_sync_on_first_run call and
@@ -330,7 +453,7 @@ class _CompoundListener(_InstanceLevelDispatch):
         else:
             self(*args, **kw)
 
-    def __call__(self, *args, **kw):
+    def __call__(self, *args: Any, **kw: Any) -> None:
         """Execute this event."""
 
         for fn in self.parent_listeners:
@@ -338,19 +461,22 @@ class _CompoundListener(_InstanceLevelDispatch):
         for fn in self.listeners:
             fn(*args, **kw)
 
-    def __len__(self):
+    def __contains__(self, item: Any) -> bool:
+        return item in self.parent_listeners or item in self.listeners
+
+    def __len__(self) -> int:
         return len(self.parent_listeners) + len(self.listeners)
 
-    def __iter__(self):
+    def __iter__(self) -> Iterator[_ListenerFnType]:
         return chain(self.parent_listeners, self.listeners)
 
-    def __bool__(self):
+    def __bool__(self) -> bool:
         return bool(self.listeners or self.parent_listeners)
 
     __nonzero__ = __bool__
 
 
-class _ListenerCollection(_CompoundListener):
+class _ListenerCollection(_CompoundListener[_ET]):
     """Instance-level attributes on instances of :class:`._Dispatch`.
 
     Represents a collection of listeners.
@@ -369,7 +495,13 @@ class _ListenerCollection(_CompoundListener):
         "__weakref__",
     )
 
-    def __init__(self, parent, target_cls):
+    parent_listeners: Collection[_ListenerFnType]
+    parent: _ClsLevelDispatch[_ET]
+    name: str
+    listeners: Deque[_ListenerFnType]
+    propagate: Set[_ListenerFnType]
+
+    def __init__(self, parent: _ClsLevelDispatch[_ET], target_cls: Type[_ET]):
         if target_cls not in parent._clslevel:
             parent.update_subclass(target_cls)
         self._exec_once = False
@@ -380,7 +512,7 @@ class _ListenerCollection(_CompoundListener):
         self.listeners = collections.deque()
         self.propagate = set()
 
-    def for_modify(self, obj):
+    def for_modify(self, obj: _Dispatch[_ET]) -> _ListenerCollection[_ET]:
         """Return an event collection which can be modified.
 
         For _ListenerCollection at the instance level of
@@ -389,10 +521,11 @@ class _ListenerCollection(_CompoundListener):
         """
         return self
 
-    def _update(self, other, only_propagate=True):
+    def _update(
+        self, other: _ListenerCollection[_ET], only_propagate: bool = True
+    ) -> None:
         """Populate from the listeners in another :class:`_Dispatch`
         object."""
-
         existing_listeners = self.listeners
         existing_listener_set = set(existing_listeners)
         self.propagate.update(other.propagate)
@@ -409,56 +542,75 @@ class _ListenerCollection(_CompoundListener):
         to_associate = other.propagate.union(other_listeners)
         registry._stored_in_collection_multi(self, other, to_associate)
 
-    def insert(self, event_key, propagate):
+    def insert(self, event_key: _EventKey[_ET], propagate: bool) -> None:
         if event_key.prepend_to_list(self, self.listeners):
             if propagate:
                 self.propagate.add(event_key._listen_fn)
 
-    def append(self, event_key, propagate):
+    def append(self, event_key: _EventKey[_ET], propagate: bool) -> None:
         if event_key.append_to_list(self, self.listeners):
             if propagate:
                 self.propagate.add(event_key._listen_fn)
 
-    def remove(self, event_key):
+    def remove(self, event_key: _EventKey[_ET]) -> None:
         self.listeners.remove(event_key._listen_fn)
         self.propagate.discard(event_key._listen_fn)
         registry._removed_from_collection(event_key, self)
 
-    def clear(self):
+    def clear(self) -> None:
         registry._clear(self, self.listeners)
         self.propagate.clear()
         self.listeners.clear()
 
 
-class _JoinedListener(_CompoundListener):
-    __slots__ = "parent", "name", "local", "parent_listeners"
+class _JoinedListener(_CompoundListener[_ET]):
+    __slots__ = "parent_dispatch", "name", "local", "parent_listeners"
+
+    parent_dispatch: _Dispatch[_ET]
+    name: str
+    local: _InstanceLevelDispatch[_ET]
+    parent_listeners: Collection[_ListenerFnType]
 
-    def __init__(self, parent, name, local):
+    def __init__(
+        self,
+        parent_dispatch: _Dispatch[_ET],
+        name: str,
+        local: _EmptyListener[_ET],
+    ):
         self._exec_once = False
-        self.parent = parent
+        self.parent_dispatch = parent_dispatch
         self.name = name
         self.local = local
         self.parent_listeners = self.local
 
-    @property
-    def listeners(self):
-        return getattr(self.parent, self.name)
-
-    def _adjust_fn_spec(self, fn, named):
+    if not typing.TYPE_CHECKING:
+        # first error, I don't really understand:
+        # Signature of "listeners" incompatible with
+        # supertype "_CompoundListener"  [override]
+        # the name / return type are exactly the same
+        # second error is getattr_isn't typed, the cast() here
+        # adds too much method overhead
+        @property
+        def listeners(self) -> Collection[_ListenerFnType]:
+            return getattr(self.parent_dispatch, self.name)
+
+    def _adjust_fn_spec(
+        self, fn: _ListenerFnType, named: bool
+    ) -> _ListenerFnType:
         return self.local._adjust_fn_spec(fn, named)
 
-    def for_modify(self, obj):
+    def for_modify(self, obj: _JoinedDispatcher[_ET]) -> _JoinedListener[_ET]:
         self.local = self.parent_listeners = self.local.for_modify(obj)
         return self
 
-    def insert(self, event_key, propagate):
+    def insert(self, event_key: _EventKey[_ET], propagate: bool) -> None:
         self.local.insert(event_key, propagate)
 
-    def append(self, event_key, propagate):
+    def append(self, event_key: _EventKey[_ET], propagate: bool) -> None:
         self.local.append(event_key, propagate)
 
-    def remove(self, event_key):
+    def remove(self, event_key: _EventKey[_ET]) -> None:
         self.local.remove(event_key)
 
-    def clear(self):
+    def clear(self) -> None:
         raise NotImplementedError()
index 25d36924081e3a7718f801585fc58b43b45e88ab..0e0647036f5d2cff058b26a0ac0c6d8ec7bc46d2 100644 (file)
@@ -15,21 +15,37 @@ at the class level of a particular ``_Dispatch`` class as well as within
 instances of ``_Dispatch``.
 
 """
-from typing import ClassVar
+from __future__ import annotations
+
+from typing import Any
+from typing import cast
+from typing import Dict
+from typing import Generic
+from typing import Iterator
+from typing import List
+from typing import MutableMapping
 from typing import Optional
+from typing import overload
+from typing import Tuple
 from typing import Type
+from typing import Union
 import weakref
 
 from .attr import _ClsLevelDispatch
 from .attr import _EmptyListener
+from .attr import _InstanceLevelDispatch
 from .attr import _JoinedListener
+from .registry import _ET
+from .registry import _EventKey
 from .. import util
-from ..util.typing import Protocol
+from ..util.typing import Literal
 
-_registrars = util.defaultdict(list)
+_registrars: MutableMapping[
+    str, List[Type[_HasEventsDispatch[Any]]]
+] = util.defaultdict(list)
 
 
-def _is_event_name(name):
+def _is_event_name(name: str) -> bool:
     # _sa_event prefix is special to support internal-only event names.
     # most event names are just plain method names that aren't
     # underscored.
@@ -45,17 +61,17 @@ class _UnpickleDispatch:
 
     """
 
-    def __call__(self, _instance_cls):
+    def __call__(self, _instance_cls: Type[_ET]) -> _Dispatch[_ET]:
         for cls in _instance_cls.__mro__:
             if "dispatch" in cls.__dict__:
-                return cls.__dict__["dispatch"].dispatch._for_class(
-                    _instance_cls
-                )
+                return cast(
+                    "_Dispatch[_ET]", cls.__dict__["dispatch"].dispatch
+                )._for_class(_instance_cls)
         else:
             raise AttributeError("No class with a 'dispatch' member present.")
 
 
-class _Dispatch:
+class _Dispatch(Generic[_ET]):
     """Mirror the event listening definitions of an Events class with
     listener collections.
 
@@ -79,20 +95,35 @@ class _Dispatch:
     # so __dict__ is used in just that case and potentially others.
     __slots__ = "_parent", "_instance_cls", "__dict__", "_empty_listeners"
 
-    _empty_listener_reg = weakref.WeakKeyDictionary()
+    _empty_listener_reg: MutableMapping[
+        Type[_ET], Dict[str, _EmptyListener[_ET]]
+    ] = weakref.WeakKeyDictionary()
+
+    _empty_listeners: Dict[str, _EmptyListener[_ET]]
+
+    _event_names: List[str]
+
+    _instance_cls: Optional[Type[_ET]]
 
-    _events: Type["_HasEventsDispatch"]
+    _joined_dispatch_cls: Type[_JoinedDispatcher[_ET]]
+
+    _events: Type[_HasEventsDispatch[_ET]]
     """reference back to the Events class.
 
     Bidirectional against _HasEventsDispatch.dispatch
 
     """
 
-    def __init__(self, parent, instance_cls=None):
+    def __init__(
+        self,
+        parent: Optional[_Dispatch[_ET]],
+        instance_cls: Optional[Type[_ET]] = None,
+    ):
         self._parent = parent
         self._instance_cls = instance_cls
 
         if instance_cls:
+            assert parent is not None
             try:
                 self._empty_listeners = self._empty_listener_reg[instance_cls]
             except KeyError:
@@ -105,7 +136,7 @@ class _Dispatch:
         else:
             self._empty_listeners = {}
 
-    def __getattr__(self, name):
+    def __getattr__(self, name: str) -> _InstanceLevelDispatch[_ET]:
         # Assign EmptyListeners as attributes on demand
         # to reduce startup time for new dispatch objects.
         try:
@@ -117,24 +148,23 @@ class _Dispatch:
             return ls
 
     @property
-    def _event_descriptors(self):
+    def _event_descriptors(self) -> Iterator[_ClsLevelDispatch[_ET]]:
         for k in self._event_names:
             # Yield _ClsLevelDispatch related
             # to relevant event name.
             yield getattr(self, k)
 
-    @property
-    def _listen(self):
-        return self._events._listen
+    def _listen(self, event_key: _EventKey[_ET], **kw: Any) -> None:
+        return self._events._listen(event_key, **kw)
 
-    def _for_class(self, instance_cls):
+    def _for_class(self, instance_cls: Type[_ET]) -> _Dispatch[_ET]:
         return self.__class__(self, instance_cls)
 
-    def _for_instance(self, instance):
+    def _for_instance(self, instance: _ET) -> _Dispatch[_ET]:
         instance_cls = instance.__class__
         return self._for_class(instance_cls)
 
-    def _join(self, other):
+    def _join(self, other: _Dispatch[_ET]) -> _JoinedDispatcher[_ET]:
         """Create a 'join' of this :class:`._Dispatch` and another.
 
         This new dispatcher will dispatch events to both
@@ -147,14 +177,15 @@ class _Dispatch:
                 (_JoinedDispatcher,),
                 {"__slots__": self._event_names},
             )
-
             self.__class__._joined_dispatch_cls = cls
         return self._joined_dispatch_cls(self, other)
 
-    def __reduce__(self):
+    def __reduce__(self) -> Union[str, Tuple[Any, ...]]:
         return _UnpickleDispatch(), (self._instance_cls,)
 
-    def _update(self, other, only_propagate=True):
+    def _update(
+        self, other: _Dispatch[_ET], only_propagate: bool = True
+    ) -> None:
         """Populate from the listeners in another :class:`_Dispatch`
         object."""
         for ls in other._event_descriptors:
@@ -164,32 +195,23 @@ class _Dispatch:
                 ls, only_propagate=only_propagate
             )
 
-    def _clear(self):
+    def _clear(self) -> None:
         for ls in self._event_descriptors:
             ls.for_modify(self).clear()
 
 
-def _remove_dispatcher(cls):
+def _remove_dispatcher(cls: Type[_HasEventsDispatch[_ET]]) -> None:
     for k in cls.dispatch._event_names:
         _registrars[k].remove(cls)
         if not _registrars[k]:
             del _registrars[k]
 
 
-class _HasEventsDispatchProto(Protocol):
-    """protocol for non-event classes that will also receive the 'dispatch'
-    attribute in the form of a descriptor.
-
-    """
-
-    dispatch: ClassVar["dispatcher"]
-
-
-class _HasEventsDispatch:
-    _dispatch_target: Optional[Type[_HasEventsDispatchProto]]
+class _HasEventsDispatch(Generic[_ET]):
+    _dispatch_target: Optional[Type[_ET]]
     """class which will receive the .dispatch collection"""
 
-    dispatch: _Dispatch
+    dispatch: _Dispatch[_ET]
     """reference back to the _Dispatch class.
 
     Bidirectional against _Dispatch._events
@@ -202,19 +224,41 @@ class _HasEventsDispatch:
 
         cls._create_dispatcher_class(cls.__name__, cls.__bases__, cls.__dict__)
 
+    @classmethod
+    def _accept_with(
+        cls, target: Union[_ET, Type[_ET]]
+    ) -> Optional[Union[_ET, Type[_ET]]]:
+        raise NotImplementedError()
+
+    @classmethod
+    def _listen(
+        cls,
+        event_key: _EventKey[_ET],
+        propagate: bool = False,
+        insert: bool = False,
+        named: bool = False,
+        asyncio: bool = False,
+    ) -> None:
+        raise NotImplementedError()
+
     @staticmethod
-    def _set_dispatch(cls, dispatch_cls):
+    def _set_dispatch(
+        klass: Type[_HasEventsDispatch[_ET]],
+        dispatch_cls: Type[_Dispatch[_ET]],
+    ) -> _Dispatch[_ET]:
         # This allows an Events subclass to define additional utility
         # methods made available to the target via
         # "self.dispatch._events.<utilitymethod>"
         # @staticmethod to allow easy "super" calls while in a metaclass
         # constructor.
-        cls.dispatch = dispatch_cls(None)
-        dispatch_cls._events = cls
-        return cls.dispatch
+        klass.dispatch = dispatch_cls(None)
+        dispatch_cls._events = klass
+        return klass.dispatch
 
     @classmethod
-    def _create_dispatcher_class(cls, classname, bases, dict_):
+    def _create_dispatcher_class(
+        cls, classname: str, bases: Tuple[type, ...], dict_: Dict[str, Any]
+    ) -> None:
         """Create a :class:`._Dispatch` class corresponding to an
         :class:`.Events` class."""
 
@@ -227,14 +271,16 @@ class _HasEventsDispatch:
             dispatch_base = _Dispatch
 
         event_names = [k for k in dict_ if _is_event_name(k)]
-        dispatch_cls = type(
-            "%sDispatch" % classname,
-            (dispatch_base,),
-            {"__slots__": event_names},
+        dispatch_cls = cast(
+            "Type[_Dispatch[_ET]]",
+            type(
+                "%sDispatch" % classname,
+                (dispatch_base,),  # type: ignore
+                {"__slots__": event_names},
+            ),
         )
 
         dispatch_cls._event_names = event_names
-
         dispatch_inst = cls._set_dispatch(cls, dispatch_cls)
         for k in dispatch_cls._event_names:
             setattr(dispatch_inst, k, _ClsLevelDispatch(cls, dict_[k]))
@@ -251,23 +297,28 @@ class _HasEventsDispatch:
             assert dispatch_target_cls is not None
             if (
                 hasattr(dispatch_target_cls, "__slots__")
-                and "_slots_dispatch" in dispatch_target_cls.__slots__
+                and "_slots_dispatch" in dispatch_target_cls.__slots__  # type: ignore  # noqa E501
             ):
                 dispatch_target_cls.dispatch = slots_dispatcher(cls)
             else:
                 dispatch_target_cls.dispatch = dispatcher(cls)
 
 
-class Events(_HasEventsDispatch):
+class Events(_HasEventsDispatch[_ET]):
     """Define event listening functions for a particular target type."""
 
     @classmethod
-    def _accept_with(cls, target):
-        def dispatch_is(*types):
+    def _accept_with(
+        cls, target: Union[_ET, Type[_ET]]
+    ) -> Optional[Union[_ET, Type[_ET]]]:
+        def dispatch_is(*types: Type[Any]) -> bool:
             return all(isinstance(target.dispatch, t) for t in types)
 
-        def dispatch_parent_is(t):
-            return isinstance(target.dispatch.parent, t)
+        def dispatch_parent_is(t: Type[Any]) -> bool:
+
+            return isinstance(
+                cast("_JoinedDispatcher[_ET]", target.dispatch).parent, t
+            )
 
         # Mapper, ClassManager, Session override this to
         # also accept classes, scoped_sessions, sessionmakers, etc.
@@ -282,39 +333,45 @@ class Events(_HasEventsDispatch):
             ):
                 return target
 
+        return None
+
     @classmethod
     def _listen(
         cls,
-        event_key,
-        propagate=False,
-        insert=False,
-        named=False,
-        asyncio=False,
-    ):
+        event_key: _EventKey[_ET],
+        propagate: bool = False,
+        insert: bool = False,
+        named: bool = False,
+        asyncio: bool = False,
+    ) -> None:
         event_key.base_listen(
             propagate=propagate, insert=insert, named=named, asyncio=asyncio
         )
 
     @classmethod
-    def _remove(cls, event_key):
+    def _remove(cls, event_key: _EventKey[_ET]) -> None:
         event_key.remove()
 
     @classmethod
-    def _clear(cls):
+    def _clear(cls) -> None:
         cls.dispatch._clear()
 
 
-class _JoinedDispatcher:
+class _JoinedDispatcher(Generic[_ET]):
     """Represent a connection between two _Dispatch objects."""
 
     __slots__ = "local", "parent", "_instance_cls"
 
-    def __init__(self, local, parent):
+    local: _Dispatch[_ET]
+    parent: _Dispatch[_ET]
+    _instance_cls: Optional[Type[_ET]]
+
+    def __init__(self, local: _Dispatch[_ET], parent: _Dispatch[_ET]):
         self.local = local
         self.parent = parent
         self._instance_cls = self.local._instance_cls
 
-    def __getattr__(self, name):
+    def __getattr__(self, name: str) -> _JoinedListener[_ET]:
         # Assign _JoinedListeners as attributes on demand
         # to reduce startup time for new dispatch objects.
         ls = getattr(self.local, name)
@@ -322,16 +379,15 @@ class _JoinedDispatcher:
         setattr(self, ls.name, jl)
         return jl
 
-    @property
-    def _listen(self):
-        return self.parent._listen
+    def _listen(self, event_key: _EventKey[_ET], **kw: Any) -> None:
+        return self.parent._listen(event_key, **kw)
 
     @property
-    def _events(self):
+    def _events(self) -> Type[_HasEventsDispatch[_ET]]:
         return self.parent._events
 
 
-class dispatcher:
+class dispatcher(Generic[_ET]):
     """Descriptor used by target classes to
     deliver the _Dispatch class at the class level
     and produce new _Dispatch instances for target
@@ -339,11 +395,21 @@ class dispatcher:
 
     """
 
-    def __init__(self, events):
+    def __init__(self, events: Type[_HasEventsDispatch[_ET]]):
         self.dispatch = events.dispatch
         self.events = events
 
-    def __get__(self, obj, cls):
+    @overload
+    def __get__(
+        self, obj: Literal[None], cls: Type[Any]
+    ) -> Type[_HasEventsDispatch[_ET]]:
+        ...
+
+    @overload
+    def __get__(self, obj: Any, cls: Type[Any]) -> _HasEventsDispatch[_ET]:
+        ...
+
+    def __get__(self, obj: Any, cls: Type[Any]) -> Any:
         if obj is None:
             return self.dispatch
 
@@ -358,8 +424,8 @@ class dispatcher:
         return disp
 
 
-class slots_dispatcher(dispatcher):
-    def __get__(self, obj, cls):
+class slots_dispatcher(dispatcher[_ET]):
+    def __get__(self, obj: Any, cls: Type[Any]) -> Any:
         if obj is None:
             return self.dispatch
 
index 053b47eaac45576ff26b810ee86ffe766aa905c1..75e5be7fe08d14a1a901ff68fd48c6f727cf1f80 100644 (file)
@@ -9,11 +9,34 @@
 generation of deprecation notes and docstrings.
 
 """
-
+from __future__ import annotations
+
+import typing
+from typing import Any
+from typing import Callable
+from typing import List
+from typing import Optional
+from typing import Tuple
+from typing import Type
+
+from .registry import _ET
+from .registry import _ListenerFnType
 from .. import util
+from ..util.compat import FullArgSpec
+
+if typing.TYPE_CHECKING:
+    from .attr import _ClsLevelDispatch
+    from .base import _HasEventsDispatch
+
+
+_LegacySignatureType = Tuple[str, List[str], Optional[Callable[..., Any]]]
 
 
-def _legacy_signature(since, argnames, converter=None):
+def _legacy_signature(
+    since: str,
+    argnames: List[str],
+    converter: Optional[Callable[..., Any]] = None,
+) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
     """legacy sig decorator
 
 
@@ -25,16 +48,20 @@ def _legacy_signature(since, argnames, converter=None):
 
     """
 
-    def leg(fn):
+    def leg(fn: Callable[..., Any]) -> Callable[..., Any]:
         if not hasattr(fn, "_legacy_signatures"):
-            fn._legacy_signatures = []
-        fn._legacy_signatures.append((since, argnames, converter))
+            fn._legacy_signatures = []  # type: ignore[attr-defined]
+        fn._legacy_signatures.append((since, argnames, converter))  # type: ignore[attr-defined] # noqa E501
         return fn
 
     return leg
 
 
-def _wrap_fn_for_legacy(dispatch_collection, fn, argspec):
+def _wrap_fn_for_legacy(
+    dispatch_collection: "_ClsLevelDispatch[_ET]",
+    fn: _ListenerFnType,
+    argspec: FullArgSpec,
+) -> _ListenerFnType:
     for since, argnames, conv in dispatch_collection.legacy_signatures:
         if argnames[-1] == "**kw":
             has_kw = True
@@ -64,34 +91,39 @@ def _wrap_fn_for_legacy(dispatch_collection, fn, argspec):
                 )
             )
 
-            if conv:
+            if conv is not None:
                 assert not has_kw
 
-                def wrap_leg(*args):
+                def wrap_leg(*args: Any, **kw: Any) -> Any:
                     util.warn_deprecated(warning_txt, version=since)
+                    assert conv is not None
                     return fn(*conv(*args))
 
             else:
 
-                def wrap_leg(*args, **kw):
+                def wrap_leg(*args: Any, **kw: Any) -> Any:
                     util.warn_deprecated(warning_txt, version=since)
                     argdict = dict(zip(dispatch_collection.arg_names, args))
-                    args = [argdict[name] for name in argnames]
+                    args_from_dict = [argdict[name] for name in argnames]
                     if has_kw:
-                        return fn(*args, **kw)
+                        return fn(*args_from_dict, **kw)
                     else:
-                        return fn(*args)
+                        return fn(*args_from_dict)
 
             return wrap_leg
     else:
         return fn
 
 
-def _indent(text, indent):
+def _indent(text: str, indent: str) -> str:
     return "\n".join(indent + line for line in text.split("\n"))
 
 
-def _standard_listen_example(dispatch_collection, sample_target, fn):
+def _standard_listen_example(
+    dispatch_collection: "_ClsLevelDispatch[_ET]",
+    sample_target: Any,
+    fn: _ListenerFnType,
+) -> str:
     example_kw_arg = _indent(
         "\n".join(
             "%(arg)s = kw['%(arg)s']" % {"arg": arg}
@@ -128,7 +160,11 @@ def _standard_listen_example(dispatch_collection, sample_target, fn):
     return text
 
 
-def _legacy_listen_examples(dispatch_collection, sample_target, fn):
+def _legacy_listen_examples(
+    dispatch_collection: "_ClsLevelDispatch[_ET]",
+    sample_target: str,
+    fn: _ListenerFnType,
+) -> str:
     text = ""
     for since, args, conv in dispatch_collection.legacy_signatures:
         text += (
@@ -152,7 +188,10 @@ def _legacy_listen_examples(dispatch_collection, sample_target, fn):
     return text
 
 
-def _version_signature_changes(parent_dispatch_cls, dispatch_collection):
+def _version_signature_changes(
+    parent_dispatch_cls: Type["_HasEventsDispatch[_ET]"],
+    dispatch_collection: "_ClsLevelDispatch[_ET]",
+) -> str:
     since, args, conv = dispatch_collection.legacy_signatures[0]
     return (
         "\n.. deprecated:: %(since)s\n"
@@ -171,7 +210,11 @@ def _version_signature_changes(parent_dispatch_cls, dispatch_collection):
     )
 
 
-def _augment_fn_docs(dispatch_collection, parent_dispatch_cls, fn):
+def _augment_fn_docs(
+    dispatch_collection: "_ClsLevelDispatch[_ET]",
+    parent_dispatch_cls: Type["_HasEventsDispatch[_ET]"],
+    fn: _ListenerFnType,
+) -> str:
     header = (
         ".. container:: event_signatures\n\n"
         "     Example argument forms::\n"
index d831a332fcdce5ddb8724f20518f5afa862ace5c..e20d3e0b53649d07fbae1659f8f6ed328693f857 100644 (file)
@@ -14,15 +14,60 @@ membership in all those collections can be revoked at once, based on
 an equivalent :class:`._EventKey`.
 
 """
+from __future__ import annotations
+
 import collections
 import types
+import typing
+from typing import Any
+from typing import Callable
+from typing import cast
+from typing import ClassVar
+from typing import Deque
+from typing import Dict
+from typing import Generic
+from typing import Iterable
+from typing import Optional
+from typing import Tuple
+from typing import TypeVar
+from typing import Union
 import weakref
 
 from .. import exc
 from .. import util
+from ..util.typing import Protocol
+
+if typing.TYPE_CHECKING:
+    from .attr import RefCollection
+    from .base import dispatcher
+
+_ListenerFnType = Callable[..., Any]
+_ListenerFnKeyType = Union[int, Tuple[int, int]]
+_EventKeyTupleType = Tuple[int, str, _ListenerFnKeyType]
+
+
+class _EventTargetType(Protocol):
+    """represents an event target, that is, something we can listen on
+    either with that target as a class or as an instance.
+
+    Examples include:  Connection, Mapper, Table, Session,
+    InstrumentedAttribute, Engine, Pool, Dialect.
 
+    """
 
-_key_to_collection = collections.defaultdict(dict)
+    dispatch: ClassVar[dispatcher[Any]]
+
+
+_ET = TypeVar("_ET", bound=_EventTargetType)
+
+_RefCollectionToListenerType = Dict[
+    "weakref.ref[RefCollection[Any]]",
+    "weakref.ref[_ListenerFnType]",
+]
+
+_key_to_collection: Dict[
+    _EventKeyTupleType, _RefCollectionToListenerType
+] = collections.defaultdict(dict)
 """
 Given an original listen() argument, can locate all
 listener collections and the listener fn contained
@@ -34,7 +79,14 @@ listener collections and the listener fn contained
                         }
 """
 
-_collection_to_key = collections.defaultdict(dict)
+_ListenerToEventKeyType = Dict[
+    "weakref.ref[_ListenerFnType]",
+    _EventKeyTupleType,
+]
+_collection_to_key: Dict[
+    weakref.ref[RefCollection[Any]],
+    _ListenerToEventKeyType,
+] = collections.defaultdict(dict)
 """
 Given a _ListenerCollection or _ClsLevelListener, can locate
 all the original listen() arguments and the listener fn contained
@@ -47,10 +99,13 @@ ref(listenercollection) -> {
 """
 
 
-def _collection_gced(ref):
+def _collection_gced(ref: weakref.ref[Any]) -> None:
     # defaultdict, so can't get a KeyError
     if not _collection_to_key or ref not in _collection_to_key:
         return
+
+    ref = cast("weakref.ref[RefCollection[_EventTargetType]]", ref)
+
     listener_to_key = _collection_to_key.pop(ref)
     for key in listener_to_key.values():
         if key in _key_to_collection:
@@ -61,7 +116,9 @@ def _collection_gced(ref):
                 _key_to_collection.pop(key)
 
 
-def _stored_in_collection(event_key, owner):
+def _stored_in_collection(
+    event_key: _EventKey[_ET], owner: RefCollection[_ET]
+) -> bool:
     key = event_key._key
 
     dispatch_reg = _key_to_collection[key]
@@ -80,7 +137,9 @@ def _stored_in_collection(event_key, owner):
     return True
 
 
-def _removed_from_collection(event_key, owner):
+def _removed_from_collection(
+    event_key: _EventKey[_ET], owner: RefCollection[_ET]
+) -> None:
     key = event_key._key
 
     dispatch_reg = _key_to_collection[key]
@@ -97,15 +156,19 @@ def _removed_from_collection(event_key, owner):
         listener_to_key.pop(listen_ref)
 
 
-def _stored_in_collection_multi(newowner, oldowner, elements):
+def _stored_in_collection_multi(
+    newowner: RefCollection[_ET],
+    oldowner: RefCollection[_ET],
+    elements: Iterable[_ListenerFnType],
+) -> None:
     if not elements:
         return
 
-    oldowner = oldowner.ref
-    newowner = newowner.ref
+    oldowner_ref = oldowner.ref
+    newowner_ref = newowner.ref
 
-    old_listener_to_key = _collection_to_key[oldowner]
-    new_listener_to_key = _collection_to_key[newowner]
+    old_listener_to_key = _collection_to_key[oldowner_ref]
+    new_listener_to_key = _collection_to_key[newowner_ref]
 
     for listen_fn in elements:
         listen_ref = weakref.ref(listen_fn)
@@ -121,31 +184,34 @@ def _stored_in_collection_multi(newowner, oldowner, elements):
         except KeyError:
             continue
 
-        if newowner in dispatch_reg:
-            assert dispatch_reg[newowner] == listen_ref
+        if newowner_ref in dispatch_reg:
+            assert dispatch_reg[newowner_ref] == listen_ref
         else:
-            dispatch_reg[newowner] = listen_ref
+            dispatch_reg[newowner_ref] = listen_ref
 
         new_listener_to_key[listen_ref] = key
 
 
-def _clear(owner, elements):
+def _clear(
+    owner: RefCollection[_ET],
+    elements: Iterable[_ListenerFnType],
+) -> None:
     if not elements:
         return
 
-    owner = owner.ref
-    listener_to_key = _collection_to_key[owner]
+    owner_ref = owner.ref
+    listener_to_key = _collection_to_key[owner_ref]
     for listen_fn in elements:
         listen_ref = weakref.ref(listen_fn)
         key = listener_to_key[listen_ref]
         dispatch_reg = _key_to_collection[key]
-        dispatch_reg.pop(owner, None)
+        dispatch_reg.pop(owner_ref, None)
 
         if not dispatch_reg:
             del _key_to_collection[key]
 
 
-class _EventKey:
+class _EventKey(Generic[_ET]):
     """Represent :func:`.listen` arguments."""
 
     __slots__ = (
@@ -157,10 +223,24 @@ class _EventKey:
         "dispatch_target",
     )
 
-    def __init__(self, target, identifier, fn, dispatch_target, _fn_wrap=None):
+    target: _ET
+    identifier: str
+    fn: _ListenerFnType
+    fn_key: _ListenerFnKeyType
+    dispatch_target: Any
+    _fn_wrap: Optional[_ListenerFnType]
+
+    def __init__(
+        self,
+        target: _ET,
+        identifier: str,
+        fn: _ListenerFnType,
+        dispatch_target: Any,
+        _fn_wrap: Optional[_ListenerFnType] = None,
+    ):
         self.target = target
         self.identifier = identifier
-        self.fn = fn
+        self.fn = fn  # type: ignore[assignment]
         if isinstance(fn, types.MethodType):
             self.fn_key = id(fn.__func__), id(fn.__self__)
         else:
@@ -169,10 +249,10 @@ class _EventKey:
         self.dispatch_target = dispatch_target
 
     @property
-    def _key(self):
+    def _key(self) -> _EventKeyTupleType:
         return (id(self.target), self.identifier, self.fn_key)
 
-    def with_wrapper(self, fn_wrap):
+    def with_wrapper(self, fn_wrap: _ListenerFnType) -> _EventKey[_ET]:
         if fn_wrap is self._listen_fn:
             return self
         else:
@@ -184,7 +264,7 @@ class _EventKey:
                 _fn_wrap=fn_wrap,
             )
 
-    def with_dispatch_target(self, dispatch_target):
+    def with_dispatch_target(self, dispatch_target: Any) -> _EventKey[_ET]:
         if dispatch_target is self.dispatch_target:
             return self
         else:
@@ -196,7 +276,7 @@ class _EventKey:
                 _fn_wrap=self.fn_wrap,
             )
 
-    def listen(self, *args, **kw):
+    def listen(self, *args: Any, **kw: Any) -> None:
         once = kw.pop("once", False)
         once_unless_exception = kw.pop("_once_unless_exception", False)
         named = kw.pop("named", False)
@@ -228,7 +308,7 @@ class _EventKey:
         else:
             self.dispatch_target.dispatch._listen(self, *args, **kw)
 
-    def remove(self):
+    def remove(self) -> None:
         key = self._key
 
         if key not in _key_to_collection:
@@ -245,18 +325,18 @@ class _EventKey:
             if collection is not None and listener_fn is not None:
                 collection.remove(self.with_wrapper(listener_fn))
 
-    def contains(self):
+    def contains(self) -> bool:
         """Return True if this event key is registered to listen."""
         return self._key in _key_to_collection
 
     def base_listen(
         self,
-        propagate=False,
-        insert=False,
-        named=False,
-        retval=None,
-        asyncio=False,
-    ):
+        propagate: bool = False,
+        insert: bool = False,
+        named: bool = False,
+        retval: Optional[bool] = None,
+        asyncio: bool = False,
+    ) -> None:
 
         target, identifier = self.dispatch_target, self.identifier
 
@@ -272,21 +352,33 @@ class _EventKey:
             for_modify.append(self, propagate)
 
     @property
-    def _listen_fn(self):
+    def _listen_fn(self) -> _ListenerFnType:
         return self.fn_wrap or self.fn
 
-    def append_to_list(self, owner, list_):
+    def append_to_list(
+        self,
+        owner: RefCollection[_ET],
+        list_: Deque[_ListenerFnType],
+    ) -> bool:
         if _stored_in_collection(self, owner):
             list_.append(self._listen_fn)
             return True
         else:
             return False
 
-    def remove_from_list(self, owner, list_):
+    def remove_from_list(
+        self,
+        owner: RefCollection[_ET],
+        list_: Deque[_ListenerFnType],
+    ) -> None:
         _removed_from_collection(self, owner)
         list_.remove(self._listen_fn)
 
-    def prepend_to_list(self, owner, list_):
+    def prepend_to_list(
+        self,
+        owner: RefCollection[_ET],
+        list_: Deque[_ListenerFnType],
+    ) -> bool:
         if _stored_in_collection(self, owner):
             list_.appendleft(self._listen_fn)
             return True
index d17b0b12f5900775e3a09a1d2e7913af15bdd5c0..4a8a52337576785a05bde6c25e7fb97a1675bf12 100644 (file)
@@ -7,6 +7,8 @@
 
 """Core event interfaces."""
 
+from __future__ import annotations
+
 from .engine.events import ConnectionEvents
 from .engine.events import DialectEvents
 from .pool.events import PoolEvents
index 6732edd4e84030e3142b0b5323a165cbb190d78c..f39f4cd8fa08d3e44dc8e38a154491f8dd2d4a17 100644 (file)
@@ -12,6 +12,8 @@ raised as a result of DBAPI exceptions are all subclasses of
 :exc:`.DBAPIError`.
 
 """
+from __future__ import annotations
+
 import typing
 from typing import Any
 from typing import List
index 4e244b5b9eba8b40e38ff2349a221def5651fb24..bfc3459d031078e090af790435c7871c397685c2 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from typing import List
 from typing import Optional
 from typing import Union
index bd6c6f41e8e833521db2ce9f82cfc8809cbb149b..13ba2e66629783dd58c8d2723dae326693457563 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from typing import List
 from typing import Optional
 from typing import Union
index 6a5e99e480eee71dce5cf94d8d830122489647e8..08035d74cd792a8f909c73aaab037f409245f837 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from typing import Optional
 from typing import Sequence
 
index ad4449e5bb8943c87ed7386e0509ffcf2883d85f..8232ca6dbd7a55ea83091f6de91c860f63a7e49b 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from typing import Dict
 from typing import List
 from typing import Optional
index c9520fef333f9c8243da4b547a6b11ab157b4a10..3a78ab188cb61e775acdeb0809adb96e8b81174b 100644 (file)
@@ -9,6 +9,8 @@
 Mypy plugin for SQLAlchemy ORM.
 
 """
+from __future__ import annotations
+
 from typing import Callable
 from typing import List
 from typing import Optional
index 741772eacd03ee81b14ff842a87dede0ecd94990..943c71b367ddf609086b0c12bc89c02250926a5e 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
 import re
 from typing import Any
 from typing import Iterable
index 5384851b10efd89722d50a7f89276874bc0e65b5..612b6272455c4f5dac761f40641c0fbe4fc52c3c 100644 (file)
@@ -119,6 +119,8 @@ start numbering at 1 or some other integer, provide ``count_from=1``.
 
 
 """
+from __future__ import annotations
+
 from typing import Callable
 from typing import List
 from typing import Optional
index c6e9ca69af94d36a0120b680baa5bc41f9e81574..6b06c0d6b64b2b153efe973cdeb599e11c3a9891 100644 (file)
@@ -28,6 +28,8 @@ tools which build on top of SQLAlchemy configurations to be constructed
 in a forwards-compatible way.
 
 """
+from __future__ import annotations
+
 from typing import Any
 from typing import Callable
 from typing import Dict
index c6a8b6ea7ff267993936b04c42eb3f63af85fc77..2f63b8569d781236df3ac0961bb77ca99d687d8e 100644 (file)
@@ -17,6 +17,8 @@ and :class:`_pool.Pool` objects, corresponds to a logger specific to that
 instance only.
 
 """
+from __future__ import annotations
+
 import logging
 import sys
 from typing import Any
index bbed9331043c9588538401cd9e4b97b88bbcaffb..5a8a0f6cf60143f8553fda527a69d631f790f59a 100644 (file)
@@ -13,6 +13,8 @@ documentation for an overview of how this module is used.
 
 """
 
+from __future__ import annotations
+
 from . import exc as exc
 from . import mapper as mapperlib
 from . import strategy_options as strategy_options
index a1f1faa053bb95caa956b567510f895f26905ce0..8e05c6ef2898493ad55b6dc57c60eb2a04789c3a 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import typing
 from typing import Any
 from typing import Collection
@@ -59,7 +61,7 @@ SynonymProperty = Synonym
     "for entities to be matched up to a query that is established "
     "via :meth:`.Query.from_statement` and now does nothing.",
 )
-def contains_alias(alias) -> "AliasOption":
+def contains_alias(alias) -> AliasOption:
     r"""Return a :class:`.MapperOption` that will indicate to the
     :class:`_query.Query`
     that the main table has been aliased.
@@ -74,7 +76,7 @@ def contains_alias(alias) -> "AliasOption":
 
 @overload
 def mapped_column(
-    __type: Union[Type["TypeEngine[_T]"], "TypeEngine[_T]"],
+    __type: Union[Type[TypeEngine[_T]], TypeEngine[_T]],
     *args: SchemaEventTarget,
     nullable: Literal[None] = ...,
     primary_key: Literal[None] = ...,
@@ -87,7 +89,7 @@ def mapped_column(
 @overload
 def mapped_column(
     __name: str,
-    __type: Union[Type["TypeEngine[_T]"], "TypeEngine[_T]"],
+    __type: Union[Type[TypeEngine[_T]], TypeEngine[_T]],
     *args: SchemaEventTarget,
     nullable: Literal[None] = ...,
     primary_key: Literal[None] = ...,
@@ -100,7 +102,7 @@ def mapped_column(
 @overload
 def mapped_column(
     __name: str,
-    __type: Union[Type["TypeEngine[_T]"], "TypeEngine[_T]"],
+    __type: Union[Type[TypeEngine[_T]], TypeEngine[_T]],
     *args: SchemaEventTarget,
     nullable: Literal[True] = ...,
     primary_key: Literal[None] = ...,
@@ -112,7 +114,7 @@ def mapped_column(
 
 @overload
 def mapped_column(
-    __type: Union[Type["TypeEngine[_T]"], "TypeEngine[_T]"],
+    __type: Union[Type[TypeEngine[_T]], TypeEngine[_T]],
     *args: SchemaEventTarget,
     nullable: Literal[True] = ...,
     primary_key: Literal[None] = ...,
@@ -125,7 +127,7 @@ def mapped_column(
 @overload
 def mapped_column(
     __name: str,
-    __type: Union[Type["TypeEngine[_T]"], "TypeEngine[_T]"],
+    __type: Union[Type[TypeEngine[_T]], TypeEngine[_T]],
     *args: SchemaEventTarget,
     nullable: Literal[False] = ...,
     primary_key: Literal[None] = ...,
@@ -137,7 +139,7 @@ def mapped_column(
 
 @overload
 def mapped_column(
-    __type: Union[Type["TypeEngine[_T]"], "TypeEngine[_T]"],
+    __type: Union[Type[TypeEngine[_T]], TypeEngine[_T]],
     *args: SchemaEventTarget,
     nullable: Literal[False] = ...,
     primary_key: Literal[None] = ...,
@@ -149,7 +151,7 @@ def mapped_column(
 
 @overload
 def mapped_column(
-    __type: Union[Type["TypeEngine[_T]"], "TypeEngine[_T]"],
+    __type: Union[Type[TypeEngine[_T]], TypeEngine[_T]],
     *args: SchemaEventTarget,
     nullable: bool = ...,
     primary_key: Literal[True] = ...,
@@ -162,7 +164,7 @@ def mapped_column(
 @overload
 def mapped_column(
     __name: str,
-    __type: Union[Type["TypeEngine[_T]"], "TypeEngine[_T]"],
+    __type: Union[Type[TypeEngine[_T]], TypeEngine[_T]],
     *args: SchemaEventTarget,
     nullable: bool = ...,
     primary_key: Literal[True] = ...,
index fbfb2b2ee0e0cc5ac705fa491e95177ea4adcfe3..c4afdb3a9ebe5ab5829635a439afe60bdb7a84af 100644 (file)
@@ -13,6 +13,9 @@ defines a large part of the ORM's interactivity.
 
 
 """
+
+from __future__ import annotations
+
 from collections import namedtuple
 import operator
 from typing import Any
index e6d4a67298f2670a77acc88abc063f493091060b..33367c0c654f5ebb825009a3056acff88b90bcb5 100644 (file)
@@ -9,6 +9,8 @@
 
 """
 
+from __future__ import annotations
+
 import operator
 import typing
 from typing import Any
index 037b70257b2aef02058983fcf3f95ab1bb2fd20f..d0cb53e29b3e9fd4f19842d79cb7d981979dd3a2 100644 (file)
@@ -10,6 +10,9 @@ This system allows specification of classes and expressions used in
 :func:`_orm.relationship` using strings.
 
 """
+
+from __future__ import annotations
+
 import re
 from typing import MutableMapping
 from typing import Union
index ba4225563d82d457443095672ee5fde08230ac30..00ae9dac7501d3da729fa89d541fabdf79a6040f 100644 (file)
@@ -102,6 +102,8 @@ The owning object and :class:`.CollectionAttributeImpl` are also reachable
 through the adapter, allowing for some very sophisticated behavior.
 
 """
+from __future__ import annotations
+
 import operator
 import threading
 import typing
index 34f291864f906d0afa258a08447cff852d846bb9..f51abde0c3ebabf1c3046dcf1e50a141fcf46650 100644 (file)
@@ -4,6 +4,9 @@
 #
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
+
+from __future__ import annotations
+
 import itertools
 from typing import List
 
index 5ac9966dd059d67aa91b8d5cd36ff383a3ce213e..4e28eeff7f95e6d81502fc18be5e4b087ceec917 100644 (file)
@@ -5,6 +5,9 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 """Public API functions and helpers for declarative."""
+
+from __future__ import annotations
+
 import itertools
 import re
 import typing
index 14812f2c29fd8a01f6477f529d8e58fce1727783..d05d27b0e079642edcb4ce8d1f620ed5340e00d4 100644 (file)
@@ -9,6 +9,8 @@
 
 """
 
+from __future__ import annotations
+
 from . import attributes
 from . import exc
 from . import sync
index 4526a8b3326af98f5232aab1ceee8ef120ff5894..4616e40945ffc810312574369eed0dec0c8a88c7 100644 (file)
@@ -10,6 +10,8 @@ that exist as configurational elements, but don't participate
 as actively in the load/persist ORM loop.
 
 """
+from __future__ import annotations
+
 import inspect
 import itertools
 import operator
index 3d9c61c20536890362480caca30bf0cbf03e3c05..52a6ec4b003226acfc14492f30c3b5fa3ed9c60a 100644 (file)
@@ -12,6 +12,8 @@ basic add/delete mutation.
 
 """
 
+from __future__ import annotations
+
 from . import attributes
 from . import exc as orm_exc
 from . import interfaces
index 61e3f6e9094630872305ba137802a7fca30272c2..453fc8903cb06e6a5cb1baafd51e320d2364f2cd 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import operator
 
 from .. import exc
index cc4bedc3f837df16cdf1121329d3856c32bac389..e62a833975fda877c77a26a2a9d518cbd5ff0a83 100644 (file)
@@ -8,6 +8,8 @@
 """ORM event interfaces.
 
 """
+from __future__ import annotations
+
 import weakref
 
 from . import instrumentation
index 8dd4d90d6868384bce94118331e2639570d30454..f70ea783739509cd8b2366a0314a6db0627abca1 100644 (file)
@@ -6,6 +6,9 @@
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
 """SQLAlchemy ORM exceptions."""
+
+from __future__ import annotations
+
 from .. import exc as sa_exc
 from .. import util
 from ..exc import MultipleResultsFound  # noqa
index f8204ec775ac1333c42a6980cd7fd60dece7af9f..3caf0b22fbc4ea0ec376ef9dc7b88945212a149c 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import weakref
 
 from . import util as orm_util
index 5d0b57206033443e693c8a6d39f72f37181c086d..a050c533a51b1c6705bf49ed5c9dc25ec3874648 100644 (file)
@@ -30,6 +30,8 @@ alternate instrumentation forms.
 """
 
 
+from __future__ import annotations
+
 from . import base
 from . import collections
 from . import exc
index 1f9ec78f76f6653c613c0a76f3f854f1d5036ea7..eed97352635d1725fa2e7651c5737e7d8cbec2c8 100644 (file)
@@ -16,6 +16,8 @@ are exposed when inspecting mappings.
 
 """
 
+from __future__ import annotations
+
 import collections
 import typing
 from typing import Any
index a40437c67e82c8788ed5a25e42a98948522f0217..16ab1f4c84c09e714ded4ee1a12c1383b241ecbd 100644 (file)
@@ -13,6 +13,8 @@ as well as some of the attribute loading strategies.
 
 """
 
+from __future__ import annotations
+
 from . import attributes
 from . import exc as orm_exc
 from . import path_registry
index 75abeef4cd5a0e2678244e599cda28af7f7f2ae9..4324a000d184984f784aae4b98e12373b06b2b83 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import operator
 from typing import Any
 from typing import Callable
index cd0d1e8203a626a1d1227f3b07a5406bde03ca96..15e9b84311c73b0f70544b5f1d7a308615cec8fe 100644 (file)
@@ -14,6 +14,8 @@ This is a semi-private module; the main configurational API of the ORM is
 available in :class:`~sqlalchemy.orm.`.
 
 """
+from __future__ import annotations
+
 from collections import deque
 from functools import reduce
 from itertools import chain
index 0d87739cc196b3dc36a13f3c2485eec8a31bc4d3..9a7aa91a03bd58adb322d9378d2d86beb30581f1 100644 (file)
@@ -8,6 +8,8 @@
 
 """
 
+from __future__ import annotations
+
 from functools import reduce
 from itertools import chain
 import logging
index b3381b0390d5cab1b50facf4bcbc291ec914af16..519eb393f691baadffbd88c7c79cd12e86cd9610 100644 (file)
@@ -13,6 +13,8 @@ The functions here are called only by the unit of work functions
 in unitofwork.py.
 
 """
+from __future__ import annotations
+
 from itertools import chain
 from itertools import groupby
 from itertools import zip_longest
index f28c45fab8b426d0098d3d3c4271fefb6185fce0..9f9ca90cb42eaf995ec18e68a4f2d5da7e8da1ea 100644 (file)
@@ -12,6 +12,8 @@ mapped attributes.
 
 """
 
+from __future__ import annotations
+
 from typing import Any
 from typing import cast
 from typing import List
index 61174487ad3fe556c8c4027670c9a3e262e7bfde..3b4b082a4cafbccedea80b28887f63109df635b8 100644 (file)
@@ -18,6 +18,8 @@ ORM session, whereas the ``Select`` construct interacts directly with the
 database to return iterable result sets.
 
 """
+from __future__ import annotations
+
 import collections.abc as collections_abc
 import itertools
 import operator
index 47da85716f40a38c353517c291c4fc1c55ef4b4c..9eb80a107254f00baaf331f54b4687ad17b39beb 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from . import exc as orm_exc
 from .base import class_mapper
 from .session import Session
index 6911ab5058f651e240b428ce0a2b46717cfb24f5..4140d52c5cc15b5f8712baf1b4da0170fb3eaf77 100644 (file)
@@ -6,6 +6,8 @@
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 """Provides the Session class and related utilities."""
 
+from __future__ import annotations
+
 import contextlib
 import itertools
 import sys
index 01ee16a13f4c1851038e0dcbb37d5352c8fdf6f9..58fa3e41a1cc6ab739f4a6e54afc8a86e9b87f32 100644 (file)
@@ -12,6 +12,8 @@ defines a large part of the ORM's interactivity.
 
 """
 
+from __future__ import annotations
+
 import weakref
 
 from . import base
index 1421c1ae930eba0da9d5ae68f8347a190e459e88..1afeab05bcb20150b902d46e5ae2a7e699deb76b 100644 (file)
@@ -8,6 +8,8 @@
 
 """
 
+from __future__ import annotations
+
 import contextlib
 from enum import Enum
 from typing import Any
index 316aa7ed731e6f49fbcd903ca4ced856ed97c6d5..85e015193771529f22448405e584a75c8a5b4eeb 100644 (file)
@@ -8,6 +8,8 @@
 """sqlalchemy.orm.interfaces.LoaderStrategy
    implementations, and related MapperOptions."""
 
+from __future__ import annotations
+
 import collections
 import itertools
 
index 3f093e543d4b79f73005cd28a0551d6056d4be64..63679dd27528e891f447f4957fc9f6b9604c77cf 100644 (file)
@@ -8,6 +8,8 @@
 
 """
 
+from __future__ import annotations
+
 import typing
 from typing import Any
 from typing import cast
index 2994841f58819654e3ef14600b7485ee3c4c5604..a49bd6f8ee2dad33221606e48734cfa1740ea3f0 100644 (file)
@@ -10,6 +10,8 @@ between instances based on join conditions.
 
 """
 
+from __future__ import annotations
+
 from . import attributes
 from . import exc
 from . import util as orm_util
index b478f427cc9e203e9edb9812ef12ea645a5e1f54..da098e8c5f770408cad27ab4f753d415a0670602 100644 (file)
@@ -13,6 +13,8 @@ organizes them in order of dependency, and executes.
 
 """
 
+from __future__ import annotations
+
 from . import attributes
 from . import exc as orm_exc
 from . import util as orm_util
index 45c578355ae8d0617ed53e84f0660f024c3288c3..e00e05954653b17509cb6a07312de538efa6fb78 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import re
 import types
 import typing
index 6c770e201c9589908396353da214652cb6f2773b..72c56716f118d892f675171fedd92e4d1f6d6656 100644 (file)
@@ -10,6 +10,8 @@
 
 """
 
+from __future__ import annotations
+
 from collections import deque
 import time
 from typing import Any
index b2ca1cfefaca34f1bc5e3051279d395adc894a9e..70a982ce245646b87e5f2149b648b7e0abdc6061 100644 (file)
@@ -9,6 +9,8 @@
 
 """
 
+from __future__ import annotations
+
 from .sql.base import SchemaVisitor as SchemaVisitor
 from .sql.ddl import _CreateDropBase as _CreateDropBase
 from .sql.ddl import _DDLCompiles as _DDLCompiles
index e62edf5e61d3e5d82b99fdcba3bb33e733697e69..a8c24413fc32bf38ba953e0d14e7bde4b35b273c 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from .dml import Delete
 from .dml import Insert
 from .dml import Update
index a8c9372e0f43fed3943116255c75e74af28e707f..4132ac6798799ca93b3501d91e5d8eb5893d7611 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import typing
 from typing import Any
 from typing import cast as _typing_cast
index 594967a40b65fe67d99f7a8a3834b8b4015adb23..96e8f6b2c796cb1892bc54b17f431398c08507f3 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from typing import Dict
 
 
index d3cf207da0a9e88562ddac1f9720c49e936c7b2c..9043aa6d05f5bd74ce99c9d52593adcc30684202 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from typing import Any
 from typing import Union
 
index 4d2dd268849e268fc2800c3d96942c1aef8db04c..7d8b9ee5c4c6efc23b9f549a9e2fdbef0227e58d 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
 from typing import Any
 from typing import Mapping
 from typing import Sequence
index c879bfc2d304630e9446990609d8094580f804f6..b76393ad6bd365092f676e04b001da2a73b90b53 100644 (file)
@@ -11,6 +11,8 @@ associations.
 
 """
 
+from __future__ import annotations
+
 from . import operators
 from .base import HasCacheKey
 from .traversals import anon_map
index 5828f9369d0b86b1375c189bbc2a59e3ee9f2ea9..3936ed9c63974ca0e0f776e6eb08bc0a3c307bc2 100644 (file)
@@ -10,6 +10,8 @@
 """
 
 
+from __future__ import annotations
+
 import collections.abc as collections_abc
 from functools import reduce
 import itertools
index 42bd603537146ed731f72146b8b2a805c91586e4..49f1899d5a723ed9feae28a4dfbd3ad6d2730205 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from collections import namedtuple
 import enum
 from itertools import zip_longest
index d5a75a16585efbdae020fdc4818f1b960b516e62..d616417ab3facc7f3bd2b76baba4cf1b2c88dbb6 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import collections.abc as collections_abc
 import numbers
 import re
index bf78b4231aea950d8605dd5f1e4e0b928cb975fb..4a169f719da28befbe6651b3d3f58f6c180ddb76 100644 (file)
@@ -22,6 +22,8 @@ To generate user-defined SQL strings, see
 :doc:`/ext/compiler`.
 
 """
+from __future__ import annotations
+
 import collections
 import collections.abc as collections_abc
 import contextlib
index 4a0555bf4843ab7da52cdbdd1f17e70e99346c16..4292aa9162a4550929bd2e6d84a83f4065a423c4 100644 (file)
@@ -9,6 +9,8 @@
 within INSERT and UPDATE statements.
 
 """
+from __future__ import annotations
+
 import functools
 import operator
 
index f622023b029e10d077b005181be5a0ba63ebf1de..7acb69bebb57bc412e4f11ccc67fdd5431df92b7 100644 (file)
@@ -9,6 +9,8 @@ Provides the hierarchy of DDL-defining schema items as well as routines
 to invoke them for a create/drop call.
 
 """
+from __future__ import annotations
+
 import typing
 from typing import Callable
 from typing import List
index 1759e686ef72e8d2d60a3c96960daa0513bf10fd..001710d7bbfa29877ee4df958a7e92f1c943a30c 100644 (file)
@@ -8,6 +8,8 @@
 """Default implementation of SQL comparison operations.
 """
 
+from __future__ import annotations
+
 import typing
 from typing import Any
 from typing import Callable
index 33dca66cd5109328ec38ddd97f3695ba1976cd43..5aded307b68fd86b1f054bbbc053483883d1a438 100644 (file)
@@ -9,6 +9,8 @@ Provide :class:`_expression.Insert`, :class:`_expression.Update` and
 :class:`_expression.Delete`.
 
 """
+from __future__ import annotations
+
 import collections.abc as collections_abc
 import typing
 
index d14521ba73f1772cf359c50e9e4d8e8a7a9e7c24..0c532a135aa5c69a8be9b143d9e54b414ff63b39 100644 (file)
@@ -10,6 +10,8 @@
 
 """
 
+from __future__ import annotations
+
 import itertools
 import operator
 import re
index c42578986de9655f9d68b1cb534eb48426b11ec0..1a1fc4c4178c362208e51f11f035f32483e040a4 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from .base import SchemaEventTarget
 from .. import event
 
index 22195cd7c54787f07c28f6a63048fd55ccaf6cbb..36ddbf309b047c4f8c2abb25c0d414c887ac6228 100644 (file)
@@ -11,6 +11,8 @@
 """
 
 
+from __future__ import annotations
+
 from ._dml_constructors import delete as delete
 from ._dml_constructors import insert as insert
 from ._dml_constructors import update as update
index 2e6d64c5522c9ccbda44f61277a579a45269e681..eb3d17ee468284f88f3fd846270a21c26fcde8a1 100644 (file)
@@ -9,6 +9,8 @@
 
 """
 
+from __future__ import annotations
+
 from typing import Any
 from typing import TypeVar
 
index ae7358870ff850b2b18e30d4f4c23961518d8409..9d011ef53917ef18bf33bf8c08ddb1a95bbb32a3 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import collections.abc as collections_abc
 import inspect
 import itertools
index 15a1566a6f9841ab565aaa1e89006ce6ab8e9236..9b6fcdbae863c2ecd88833791dd014bf5f8710d7 100644 (file)
@@ -10,6 +10,8 @@
 
 """
 
+from __future__ import annotations
+
 import re
 
 from . import events  # noqa
index 255e77b7f975364d645a61fdbe996c2b9d3a5dc3..d4fa8042dd5d6d8084a5676c11ba14490ede7a95 100644 (file)
@@ -10,6 +10,8 @@
 
 """Defines operators used in SQL expressions."""
 
+from __future__ import annotations
+
 from operator import add as _uncast_add
 from operator import and_ as _uncast_and_
 from operator import contains as _uncast_contains
index b41ef7a5d1ce60167f966f849d39dfb735a2a304..64bd4b951b9a8512444ef9af38594ce1591c46f2 100644 (file)
@@ -4,6 +4,8 @@
 #
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
+from __future__ import annotations
+
 import typing
 
 from sqlalchemy.util.langhelpers import TypingOnly
index 9387ae030c23388a5c5724755b7fbd0390a3eea8..52869179597a46b5dedc3dcaa886a6b6cdfb0ab2 100644 (file)
@@ -28,6 +28,8 @@ Since these objects are part of the SQL expression language, they are usable
 as components in SQL expressions.
 
 """
+from __future__ import annotations
+
 import collections
 import typing
 from typing import Any
index b0985f75d8fb62fb818a13d70e158cf863269b05..7f6360edb07b76460f5b14cc244a6aac8b18a2bf 100644 (file)
@@ -11,6 +11,8 @@ SQL tables and derived rowsets.
 
 """
 
+from __future__ import annotations
+
 import collections
 from enum import Enum
 import itertools
index 0ec771cb436a8efdbeb73d8fa4427247679e445c..819f1dc9a82f51cc7a947878171f62941d967e26 100644 (file)
@@ -8,6 +8,8 @@
 """SQL specific types.
 
 """
+from __future__ import annotations
+
 import collections.abc as collections_abc
 import datetime as dt
 import decimal
index 18fd1d4b81ea0a9919dfba76d85a98659d28130e..4fa23d370cab657230949bcc428b5208f59bb4a3 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 from collections import deque
 import collections.abc as collections_abc
 import itertools
index 6b878dc70bc0c88fda4f11204b952aaaa35ffa03..f76b4e462159c4affda0832d759f20bb1d58b6ac 100644 (file)
@@ -9,6 +9,8 @@
 
 """
 
+from __future__ import annotations
+
 import typing
 from typing import Any
 from typing import Callable
index c0de1902ff791723d3e9d7cc4cbfca1a749d3b04..e3e358cdb918d06ed5caf2e2d633641bf225276d 100644 (file)
@@ -8,6 +8,8 @@
 """High level utilities which build upon other modules here.
 
 """
+from __future__ import annotations
+
 from collections import deque
 from itertools import chain
 import typing
index 640c07d6182dce4d5ff3559cd18a14153e2ae194..523426d092392e301853bc9751c200960b603111 100644 (file)
@@ -23,6 +23,8 @@ https://techspot.zzzeek.org/2008/01/23/expression-transformations/ .
 
 """
 
+from __future__ import annotations
+
 from collections import deque
 import itertools
 import operator
index 5c79422dd1434a2dd27cf591c49391ca568d29ee..2e46ed8245f5547c02733fb8c1da84eeff611ede 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import contextlib
 from itertools import filterfalse
 import re
index 5c3634c7b57072455ab02ff6705112bef2f8668f..e6c00de097ad6d930aa204f5f121b3d74f08d05f 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import collections
 import contextlib
 import re
index 21890604a3738347d3396f9c284a95a132df92b8..0acec0def9d00baef6d74691d9e6e7418005f8ce 100644 (file)
@@ -17,6 +17,8 @@
 # would run in the real world.
 
 
+from __future__ import annotations
+
 from functools import wraps
 import inspect
 
index c1ca670dac07268324dbac6e9dc5978bd1aab568..04a6a1d3ac3709474d822ed7be53785cb33e332d 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import collections
 import typing
 from typing import Any
index 1d337b28f9092986ec0f96dedd16cdf61d57fcaa..79adb8c3cd22b3c514af253ca6805b58988b0c5c 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import collections
 import re
 import typing
index 8578ca9300a587818f67b0362cfca6368609e1b2..67a3095706d1e4ed202cb2157b002e0bb52c6d4c 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import sqlalchemy as sa
 from .. import exc as sa_exc
 
index 7228e5afebb3d48653fa2f54cfc68b91226568ba..6c6b21fcec8319ee0620334272220d3377f85d93 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import re
 import sys
 
index 5d322318898c212ceb01b25a6b6ec66507bc5f5c..f336444a2655fb131a5f9f4685131c00473fa4cd 100644 (file)
@@ -9,6 +9,8 @@
 unpickling.
 """
 
+from __future__ import annotations
+
 from . import fixtures
 
 
index d02b94de6f31ed646aa594f61f2fb3b5e6c4a318..6fc5efc50a8117bb5b7c5d1558fe6e88d86b1955 100644 (file)
@@ -12,6 +12,8 @@ in a more fine-grained way than nose's profiling plugin.
 
 """
 
+from __future__ import annotations
+
 import collections
 import contextlib
 import os
index e51eb172e488ff86d09d89074913af413d2cdf08..6e5555b3305bb33d48b506c45f0fa35d753bb632 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
 import collections
 import logging
 
index 41e5d6772d8e9fe36850122fc495eca466b84dfb..a5c601995e03a9da03acd16a91ff20431a094c77 100644 (file)
@@ -15,6 +15,8 @@ to provide specific inclusion/exclusions.
 
 """
 
+from __future__ import annotations
+
 import platform
 
 from . import config
index 78bc4d26939507e308866437bdb06e0c9c9458fb..ca725976bcea4d3937f97cbcf5a7918d59d120cc 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import sys
 
 from . import config
index 52f30e1890a74cf5b6f4b22552d917eaac10d836..0cba4e16b19d322878cb332f169831e034e85b52 100644 (file)
@@ -5,6 +5,8 @@
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
+from __future__ import annotations
+
 import decimal
 import gc
 import random
index 2d65e68ec4765170e6244250decf24223a8ede47..e82566be766dbbce8a7ae7607b203131c0d941c4 100644 (file)
@@ -4,6 +4,8 @@
 #
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
+from __future__ import annotations
+
 from . import assertions
 from .. import exc as sa_exc
 from ..exc import SATestSuiteWarning
index 07263c5b9eec97bd22df28295ae4f668c90215e7..9464cc9c4ebb2bbb665ffd5cfbbb68d4d873f053 100644 (file)
@@ -9,56 +9,8 @@
 
 """
 
-__all__ = [
-    "TypeEngine",
-    "TypeDecorator",
-    "UserDefinedType",
-    "ExternalType",
-    "INT",
-    "CHAR",
-    "VARCHAR",
-    "NCHAR",
-    "NVARCHAR",
-    "TEXT",
-    "Text",
-    "FLOAT",
-    "NUMERIC",
-    "REAL",
-    "DECIMAL",
-    "TIMESTAMP",
-    "DATETIME",
-    "CLOB",
-    "BLOB",
-    "BINARY",
-    "VARBINARY",
-    "BOOLEAN",
-    "BIGINT",
-    "SMALLINT",
-    "INTEGER",
-    "DATE",
-    "TIME",
-    "TupleType",
-    "String",
-    "Integer",
-    "SmallInteger",
-    "BigInteger",
-    "Numeric",
-    "Float",
-    "DateTime",
-    "Date",
-    "Time",
-    "LargeBinary",
-    "Boolean",
-    "Unicode",
-    "Concatenable",
-    "UnicodeText",
-    "PickleType",
-    "Interval",
-    "Enum",
-    "Indexable",
-    "ARRAY",
-    "JSON",
-]
+
+from __future__ import annotations
 
 from .sql.sqltypes import _Binary
 from .sql.sqltypes import ARRAY
@@ -117,3 +69,54 @@ from .sql.type_api import TypeDecorator
 from .sql.type_api import TypeEngine
 from .sql.type_api import UserDefinedType
 from .sql.type_api import Variant
+
+__all__ = [
+    "TypeEngine",
+    "TypeDecorator",
+    "UserDefinedType",
+    "ExternalType",
+    "INT",
+    "CHAR",
+    "VARCHAR",
+    "NCHAR",
+    "NVARCHAR",
+    "TEXT",
+    "Text",
+    "FLOAT",
+    "NUMERIC",
+    "REAL",
+    "DECIMAL",
+    "TIMESTAMP",
+    "DATETIME",
+    "CLOB",
+    "BLOB",
+    "BINARY",
+    "VARBINARY",
+    "BOOLEAN",
+    "BIGINT",
+    "SMALLINT",
+    "INTEGER",
+    "DATE",
+    "TIME",
+    "TupleType",
+    "String",
+    "Integer",
+    "SmallInteger",
+    "BigInteger",
+    "Numeric",
+    "Float",
+    "DateTime",
+    "Date",
+    "Time",
+    "LargeBinary",
+    "Boolean",
+    "Unicode",
+    "Concatenable",
+    "UnicodeText",
+    "PickleType",
+    "Interval",
+    "Enum",
+    "Indexable",
+    "ARRAY",
+    "JSON",
+]
index 8509868028da73b6430b61d9c14e557153fba7ff..bbb08d91f2474dbacda2a4ae110a91d344970586 100644 (file)
@@ -6,6 +6,8 @@
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
 """Collection classes and helpers."""
+from __future__ import annotations
+
 import collections.abc as collections_abc
 import operator
 import threading
index b9e58e68cd807ba67f7e9c3e81e895398565128e..fa206670271f93491622655698053bdbdceb298a 100644 (file)
@@ -157,8 +157,7 @@ class AsyncAdaptedLock:
     def __enter__(self):
         # await is used to acquire the lock only after the first calling
         # coroutine has created the mutex.
-        await_fallback(self.mutex.acquire())
-        return self
+        return await_fallback(self.mutex.acquire())
 
     def __exit__(self, *arg, **kw):
         self.mutex.release()
index b0f8ab444ae26dc845d9f27d69a18e556e1459d1..511b93351d0eabec980663383940da95cd50cc9b 100644 (file)
@@ -9,6 +9,8 @@
 runtime.
 
 """
+from __future__ import annotations
+
 import sys
 from types import ModuleType
 import typing
index 9bf5c3546d4812471c986a40fcc67e5d0941a219..ee54180ac4cc2d743ea5b6d6a72ee86a0e8f512b 100644 (file)
@@ -1,3 +1,12 @@
+# util/_py_collections.py
+# Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
+# <see AUTHORS file>
+#
+# This module is part of SQLAlchemy and is released under
+# the MIT License: https://www.opensource.org/licenses/mit-license.php
+
+from __future__ import annotations
+
 from itertools import filterfalse
 from typing import AbstractSet
 from typing import Any
index 62cffa556edee4d7e3dab8941aec1ba62bdc6571..d30236dd9dbbddf86f1b7c3c8f5cb4075b37f73a 100644 (file)
@@ -6,6 +6,7 @@
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
 
 """Handle Python version/platform incompatibilities."""
+
 from __future__ import annotations
 
 import base64
@@ -137,6 +138,9 @@ def cmp(a, b):
 def _formatannotation(annotation, base_module=None):
     """vendored from python 3.7"""
 
+    if isinstance(annotation, str):
+        return f'"{annotation}"'
+
     if getattr(annotation, "__module__", None) == "typing":
         return f'"{repr(annotation).replace("typing.", "").replace("~", "")}"'
     if isinstance(annotation, type):
index 6b94a22948ec2396a8eae0e170c96cc43c34d4d3..778d1275b93e2a96c2992bad2966e2ef37defe80 100644 (file)
@@ -4,8 +4,10 @@
 #
 # This module is part of SQLAlchemy and is released under
 # the MIT License: https://www.opensource.org/licenses/mit-license.php
+from __future__ import annotations
 
 import asyncio  # noqa
+import typing
 
 have_greenlet = False
 greenlet_error = None
@@ -28,7 +30,7 @@ else:
         _util_async_run_coroutine_function as _util_async_run_coroutine_function,  # noqa F401, E501
     )
 
-if not have_greenlet:
+if not typing.TYPE_CHECKING and not have_greenlet:
 
     def _not_implemented():
         # this conditional is to prevent pylance from considering
index 7c25861665b7d22b01f13de0145b58d3403b59a5..f91d902dae6722f31f2836be529d8a3ee75ba3e2 100644 (file)
@@ -8,12 +8,15 @@
 """Helpers related to deprecation of functions, methods, classes, other
 functionality."""
 
+from __future__ import annotations
+
 import re
 from typing import Any
 from typing import Callable
 from typing import cast
 from typing import Optional
 from typing import Tuple
+from typing import Type
 from typing import TypeVar
 
 from . import compat
@@ -28,14 +31,22 @@ from .. import exc
 _T = TypeVar("_T", bound=Any)
 
 
-def _warn_with_version(msg, version, type_, stacklevel, code=None):
+def _warn_with_version(
+    msg: str,
+    version: str,
+    type_: Type[exc.SADeprecationWarning],
+    stacklevel: int,
+    code: Optional[str] = None,
+) -> None:
     warn = type_(msg, code=code)
     warn.deprecated_since = version
 
     _warnings_warn(warn, stacklevel=stacklevel + 1)
 
 
-def warn_deprecated(msg, version, stacklevel=3, code=None):
+def warn_deprecated(
+    msg: str, version: str, stacklevel: int = 3, code: Optional[str] = None
+) -> None:
     _warn_with_version(
         msg, version, exc.SADeprecationWarning, stacklevel, code=code
     )
index ed879894d5d396034353dda75b7bd2016dea03f1..9e024b3c039a752cedb483af8e1a2b2bcf507347 100644 (file)
@@ -9,6 +9,7 @@
 modules, classes, hierarchies, attributes, functions, and methods.
 
 """
+from __future__ import annotations
 
 import collections
 from functools import update_wrapper
@@ -452,7 +453,9 @@ def get_func_kwargs(func):
     return compat.inspect_getfullargspec(func)[0]
 
 
-def get_callable_argspec(fn, no_self=False, _is_init=False):
+def get_callable_argspec(
+    fn: Callable[..., Any], no_self: bool = False, _is_init: bool = False
+) -> compat.FullArgSpec:
     """Return the argument signature for any callable.
 
     All pure-Python callables are accepted, including
@@ -496,10 +499,12 @@ def get_callable_argspec(fn, no_self=False, _is_init=False):
             fn.__init__, no_self=no_self, _is_init=True
         )
     elif hasattr(fn, "__func__"):
-        return compat.inspect_getfullargspec(fn.__func__)
+        return compat.inspect_getfullargspec(fn.__func__)  # type: ignore[attr-defined] # noqa E501
     elif hasattr(fn, "__call__"):
-        if inspect.ismethod(fn.__call__):
-            return get_callable_argspec(fn.__call__, no_self=no_self)
+        if inspect.ismethod(fn.__call__):  # type: ignore [operator]
+            return get_callable_argspec(
+                fn.__call__, no_self=no_self  # type: ignore [operator]
+            )
         else:
             raise TypeError("Can't inspect callable: %s" % fn)
     else:
@@ -1521,7 +1526,12 @@ class hybridmethod:
 class _symbol(int):
     name: str
 
-    def __new__(cls, name, doc=None, canonical=None):
+    def __new__(
+        cls,
+        name: str,
+        doc: Optional[str] = None,
+        canonical: Optional[int] = None,
+    ) -> "_symbol":
         """Construct a new named symbol."""
         assert isinstance(name, str)
         if canonical is None:
@@ -1570,7 +1580,12 @@ class symbol:
     symbols: Dict[str, "_symbol"] = {}
     _lock = threading.Lock()
 
-    def __new__(cls, name, doc=None, canonical=None):
+    def __new__(  # type: ignore[misc]
+        cls,
+        name: str,
+        doc: Optional[str] = None,
+        canonical: Optional[int] = None,
+    ) -> _symbol:
         with cls._lock:
             sym = cls.symbols.get(name)
             if sym is None:
@@ -1730,13 +1745,15 @@ def _warnings_warn(message, category=None, stacklevel=2):
         warnings.warn(message, stacklevel=stacklevel + 1)
 
 
-def only_once(fn, retry_on_exception):
+def only_once(
+    fn: Callable[..., _T], retry_on_exception: bool
+) -> Callable[..., Optional[_T]]:
     """Decorate the given function to be a no-op after it is called exactly
     once."""
 
     once = [fn]
 
-    def go(*arg, **kw):
+    def go(*arg: Any, **kw: Any) -> Optional[_T]:
         # strong reference fn so that it isn't garbage collected,
         # which interferes with the event system's expectations
         strong_fn = fn  # noqa
@@ -1749,6 +1766,8 @@ def only_once(fn, retry_on_exception):
                     once.insert(0, once_fn)
                 raise
 
+        return None
+
     return go
 
 
@@ -1936,7 +1955,7 @@ def add_parameter_text(params, text):
     return decorate
 
 
-def _dedent_docstring(text):
+def _dedent_docstring(text: str) -> str:
     split_text = text.split("\n", 1)
     if len(split_text) == 1:
         return text
@@ -1948,8 +1967,10 @@ def _dedent_docstring(text):
         return textwrap.dedent(text)
 
 
-def inject_docstring_text(doctext, injecttext, pos):
-    doctext = _dedent_docstring(doctext or "")
+def inject_docstring_text(
+    given_doctext: Optional[str], injecttext: str, pos: int
+) -> str:
+    doctext: str = _dedent_docstring(given_doctext or "")
     lines = doctext.split("\n")
     if len(lines) == 1:
         lines.append("")
@@ -1969,7 +1990,7 @@ def inject_docstring_text(doctext, injecttext, pos):
 _param_reg = re.compile(r"(\s+):param (.+?):")
 
 
-def inject_param_text(doctext, inject_params):
+def inject_param_text(doctext: str, inject_params: Dict[str, str]) -> str:
     doclines = collections.deque(doctext.splitlines())
     lines = []
 
@@ -2012,7 +2033,7 @@ def inject_param_text(doctext, inject_params):
     return "\n".join(lines)
 
 
-def repr_tuple_names(names):
+def repr_tuple_names(names: List[str]) -> Optional[str]:
     """Trims a list of strings from the middle and return a string of up to
     four elements. Strings greater than 11 characters will be truncated"""
     if len(names) == 0:
index bbc819fc317532713ac6bc0f29e0dfa2d32c06ad..bccb16672c0f8f8df2c1acdcd2a0b58678099ea1 100644 (file)
@@ -7,6 +7,8 @@
 
 """Topological sorting algorithms."""
 
+from __future__ import annotations
+
 from .. import util
 from ..exc import CircularDependencyError
 
index 56ea4d0e061c7e16c46ae8f902be34e32b39b70c..404f239c8933bb3ac0c0c97863ba816571dafcd3 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
 import sys
 import typing
 from typing import Any
index be5dd15962c3341841bb48a08d454fc92800cf98..b6f095239035036fe21dbfda51563ecbf2ded653 100644 (file)
@@ -40,6 +40,7 @@ markers = [
 
 [tool.pyright]
 include = [
+    "lib/sqlalchemy/event/",
     "lib/sqlalchemy/events.py",
     "lib/sqlalchemy/exc.py",
     "lib/sqlalchemy/log.py",
@@ -77,6 +78,7 @@ strict = true
 # strict checking
 [[tool.mypy.overrides]]
 module = [
+    "sqlalchemy.event.*",
     "sqlalchemy.events",
     "sqlalchemy.exc",
     "sqlalchemy.inspection",
index 99abcea1c85508203b088e216cdf0741216b23b0..a8c12377da5c0a347a32dc1ca15b19aa5c41d24f 100644 (file)
--- a/setup.cfg
+++ b/setup.cfg
@@ -109,8 +109,9 @@ import-order-style = google
 application-import-names = sqlalchemy,test
 per-file-ignores =
     **/__init__.py:F401
-    test/ext/mypy/plain_files/*:F821,E501
-    test/ext/mypy/plugin_files/*:F821,E501
+    test/*:FA100
+    test/ext/mypy/plain_files/*:F821,E501,FA100
+    test/ext/mypy/plugin_files/*:F821,E501,FA100
     lib/sqlalchemy/events.py:F401
     lib/sqlalchemy/schema.py:F401
     lib/sqlalchemy/types.py:F401
diff --git a/tox.ini b/tox.ini
index 71fef2a834b16eafaa483ee776823de1642593fc..c3420a00f7c3dfb30627fb9062858feb49dfd6e5 100644 (file)
--- a/tox.ini
+++ b/tox.ini
@@ -156,6 +156,7 @@ deps=
       flake8
       flake8-import-order
       flake8-builtins
+      flake8-future-annotations
       flake8-docstrings>=1.6.0
       flake8-rst-docstrings
       # flake8-rst-docstrings dependency, leaving it here