44#
55# This module is part of SQLAlchemy and is released under
66# the MIT License: https://www.opensource.org/licenses/mit-license.php
7- # mypy: ignore-errors
87
98
109"""Dynamic collection API.
2322from typing import Any
2423from typing import Iterable
2524from typing import Iterator
25+ from typing import List
26+ from typing import Optional
27+ from typing import Tuple
28+ from typing import Type
2629from typing import TYPE_CHECKING
2730from typing import TypeVar
31+ from typing import Union
2832
2933from . import attributes
3034from . import exc as orm_exc
3135from . import relationships
3236from . import util as orm_util
37+ from .base import PassiveFlag
3338from .query import Query
3439from .session import object_session
3540from .writeonly import AbstractCollectionWriter
3944from .. import util
4045from ..engine import result
4146
47+
4248if TYPE_CHECKING :
49+ from . import QueryableAttribute
50+ from .mapper import Mapper
51+ from .relationships import _RelationshipOrderByArg
4352 from .session import Session
44-
53+ from .state import InstanceState
54+ from .util import AliasedClass
55+ from ..event import _Dispatch
56+ from ..sql .elements import ColumnElement
4557
4658_T = TypeVar ("_T" , bound = Any )
4759
4860
49- class DynamicCollectionHistory (WriteOnlyHistory ):
50- def __init__ (self , attr , state , passive , apply_to = None ):
61+ class DynamicCollectionHistory (WriteOnlyHistory [_T ]):
62+ def __init__ (
63+ self ,
64+ attr : DynamicAttributeImpl ,
65+ state : InstanceState [_T ],
66+ passive : PassiveFlag ,
67+ apply_to : Optional [DynamicCollectionHistory [_T ]] = None ,
68+ ) -> None :
5169 if apply_to :
5270 coll = AppenderQuery (attr , state ).autoflush (False )
5371 self .unchanged_items = util .OrderedIdentitySet (coll )
@@ -63,21 +81,21 @@ def __init__(self, attr, state, passive, apply_to=None):
6381
6482class DynamicAttributeImpl (WriteOnlyAttributeImpl ):
6583 _supports_dynamic_iteration = True
66- collection_history_cls = DynamicCollectionHistory
84+ collection_history_cls = DynamicCollectionHistory [Any ]
85+ query_class : Type [AppenderMixin [Any ]] # type: ignore[assignment]
6786
6887 def __init__ (
6988 self ,
70- class_ ,
71- key ,
72- typecallable ,
73- dispatch ,
74- target_mapper ,
75- order_by ,
76- query_class = None ,
77- ** kw ,
78- ):
89+ class_ : Union [Type [Any ], AliasedClass [Any ]],
90+ key : str ,
91+ dispatch : _Dispatch [QueryableAttribute [Any ]],
92+ target_mapper : Mapper [_T ],
93+ order_by : _RelationshipOrderByArg ,
94+ query_class : Optional [Type [AppenderMixin [_T ]]] = None ,
95+ ** kw : Any ,
96+ ) -> None :
7997 attributes .AttributeImpl .__init__ (
80- self , class_ , key , typecallable , dispatch , ** kw
98+ self , class_ , key , None , dispatch , ** kw
8199 )
82100 self .target_mapper = target_mapper
83101 if order_by :
@@ -102,21 +120,23 @@ class AppenderMixin(AbstractCollectionWriter[_T]):
102120
103121 """
104122
105- query_class = None
123+ query_class : Optional [Type [Query [_T ]]] = None
124+ _order_by_clauses : Tuple [ColumnElement [Any ], ...]
106125
107- def __init__ (self , attr , state ):
108- Query .__init__ (self , attr .target_mapper , None )
126+ def __init__ (
127+ self , attr : DynamicAttributeImpl , state : InstanceState [_T ]
128+ ) -> None :
129+ Query .__init__ (
130+ self , # type: ignore[arg-type]
131+ attr .target_mapper ,
132+ None ,
133+ )
109134 super ().__init__ (attr , state )
110135
111136 @property
112- def session (self ) -> Session :
137+ def session (self ) -> Optional [ Session ] :
113138 sess = object_session (self .instance )
114- if (
115- sess is not None
116- and self .autoflush
117- and sess .autoflush
118- and self .instance in sess
119- ):
139+ if sess is not None and sess .autoflush and self .instance in sess :
120140 sess .flush ()
121141 if not orm_util .has_identity (self .instance ):
122142 return None
@@ -127,7 +147,7 @@ def session(self) -> Session:
127147 def session (self , session : Session ) -> None :
128148 self .sess = session
129149
130- def _iter (self ):
150+ def _iter (self ) -> Union [ result . ScalarResult [ _T ], result . Result [ _T ]] :
131151 sess = self .session
132152 if sess is None :
133153 state = attributes .instance_state (self .instance )
@@ -141,9 +161,9 @@ def _iter(self):
141161
142162 return result .IteratorResult (
143163 result .SimpleResultMetaData ([self .attr .class_ .__name__ ]),
144- self .attr ._get_collection_history (
164+ self .attr ._get_collection_history ( # type: ignore[arg-type]
145165 attributes .instance_state (self .instance ),
146- attributes .PASSIVE_NO_INITIALIZE ,
166+ PassiveFlag .PASSIVE_NO_INITIALIZE ,
147167 ).added_items ,
148168 _source_supports_scalars = True ,
149169 ).scalars ()
@@ -155,29 +175,32 @@ def _iter(self):
155175 def __iter__ (self ) -> Iterator [_T ]:
156176 ...
157177
158- def __getitem__ (self , index : Any ) -> _T :
178+ def __getitem__ (self , index : Any ) -> Union [ _T , List [ _T ]] :
159179 sess = self .session
160180 if sess is None :
161181 return self .attr ._get_collection_history (
162182 attributes .instance_state (self .instance ),
163- attributes .PASSIVE_NO_INITIALIZE ,
183+ PassiveFlag .PASSIVE_NO_INITIALIZE ,
164184 ).indexed (index )
165185 else :
166- return self ._generate (sess ).__getitem__ (index )
186+ return self ._generate (sess ).__getitem__ (index ) # type: ignore[no-any-return] # noqa: E501
167187
168188 def count (self ) -> int :
169189 sess = self .session
170190 if sess is None :
171191 return len (
172192 self .attr ._get_collection_history (
173193 attributes .instance_state (self .instance ),
174- attributes .PASSIVE_NO_INITIALIZE ,
194+ PassiveFlag .PASSIVE_NO_INITIALIZE ,
175195 ).added_items
176196 )
177197 else :
178198 return self ._generate (sess ).count ()
179199
180- def _generate (self , sess = None ):
200+ def _generate (
201+ self ,
202+ sess : Optional [Session ] = None ,
203+ ) -> Query [_T ]:
181204 # note we're returning an entirely new Query class instance
182205 # here without any assignment capabilities; the class of this
183206 # query is determined by the session.
@@ -259,7 +282,7 @@ def remove(self, item: _T) -> None:
259282 self ._remove_impl (item )
260283
261284
262- class AppenderQuery (AppenderMixin [_T ], Query [_T ]):
285+ class AppenderQuery (AppenderMixin [_T ], Query [_T ]): # type: ignore[misc]
263286 """A dynamic query that supports basic collection storage operations.
264287
265288 Methods on :class:`.AppenderQuery` include all methods of
@@ -270,7 +293,7 @@ class AppenderQuery(AppenderMixin[_T], Query[_T]):
270293 """
271294
272295
273- def mixin_user_query (cls ) :
296+ def mixin_user_query (cls : Any ) -> type [ AppenderMixin [ Any ]] :
274297 """Return a new class with AppenderQuery functionality layered over."""
275298 name = "Appender" + cls .__name__
276299 return type (name , (AppenderMixin , cls ), {"query_class" : cls })
0 commit comments