instrumentation.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. # orm/instrumentation.py
  2. # Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: allow-untyped-defs, allow-untyped-calls
  8. """Defines SQLAlchemy's system of class instrumentation.
  9. This module is usually not directly visible to user applications, but
  10. defines a large part of the ORM's interactivity.
  11. instrumentation.py deals with registration of end-user classes
  12. for state tracking. It interacts closely with state.py
  13. and attributes.py which establish per-instance and per-class-attribute
  14. instrumentation, respectively.
  15. The class instrumentation system can be customized on a per-class
  16. or global basis using the :mod:`sqlalchemy.ext.instrumentation`
  17. module, which provides the means to build and specify
  18. alternate instrumentation forms.
  19. .. versionchanged: 0.8
  20. The instrumentation extension system was moved out of the
  21. ORM and into the external :mod:`sqlalchemy.ext.instrumentation`
  22. package. When that package is imported, it installs
  23. itself within sqlalchemy.orm so that its more comprehensive
  24. resolution mechanics take effect.
  25. """
  26. from __future__ import annotations
  27. from typing import Any
  28. from typing import Callable
  29. from typing import cast
  30. from typing import Collection
  31. from typing import Dict
  32. from typing import Generic
  33. from typing import Iterable
  34. from typing import List
  35. from typing import Optional
  36. from typing import Set
  37. from typing import Tuple
  38. from typing import Type
  39. from typing import TYPE_CHECKING
  40. from typing import TypeVar
  41. from typing import Union
  42. import weakref
  43. from . import base
  44. from . import collections
  45. from . import exc
  46. from . import interfaces
  47. from . import state
  48. from ._typing import _O
  49. from .attributes import _is_collection_attribute_impl
  50. from .. import util
  51. from ..event import EventTarget
  52. from ..util import HasMemoized
  53. from ..util.typing import Literal
  54. from ..util.typing import Protocol
  55. if TYPE_CHECKING:
  56. from ._typing import _RegistryType
  57. from .attributes import AttributeImpl
  58. from .attributes import QueryableAttribute
  59. from .collections import _AdaptedCollectionProtocol
  60. from .collections import _CollectionFactoryType
  61. from .decl_base import _MapperConfig
  62. from .events import InstanceEvents
  63. from .mapper import Mapper
  64. from .state import InstanceState
  65. from ..event import dispatcher
  66. _T = TypeVar("_T", bound=Any)
  67. DEL_ATTR = util.symbol("DEL_ATTR")
  68. class _ExpiredAttributeLoaderProto(Protocol):
  69. def __call__(
  70. self,
  71. state: state.InstanceState[Any],
  72. toload: Set[str],
  73. passive: base.PassiveFlag,
  74. ) -> None: ...
  75. class _ManagerFactory(Protocol):
  76. def __call__(self, class_: Type[_O]) -> ClassManager[_O]: ...
  77. class ClassManager(
  78. HasMemoized,
  79. Dict[str, "QueryableAttribute[Any]"],
  80. Generic[_O],
  81. EventTarget,
  82. ):
  83. """Tracks state information at the class level."""
  84. dispatch: dispatcher[ClassManager[_O]]
  85. MANAGER_ATTR = base.DEFAULT_MANAGER_ATTR
  86. STATE_ATTR = base.DEFAULT_STATE_ATTR
  87. _state_setter = staticmethod(util.attrsetter(STATE_ATTR))
  88. expired_attribute_loader: _ExpiredAttributeLoaderProto
  89. "previously known as deferred_scalar_loader"
  90. init_method: Optional[Callable[..., None]]
  91. original_init: Optional[Callable[..., None]] = None
  92. factory: Optional[_ManagerFactory]
  93. declarative_scan: Optional[weakref.ref[_MapperConfig]] = None
  94. registry: _RegistryType
  95. if not TYPE_CHECKING:
  96. # starts as None during setup
  97. registry = None
  98. class_: Type[_O]
  99. _bases: List[ClassManager[Any]]
  100. @property
  101. @util.deprecated(
  102. "1.4",
  103. message="The ClassManager.deferred_scalar_loader attribute is now "
  104. "named expired_attribute_loader",
  105. )
  106. def deferred_scalar_loader(self):
  107. return self.expired_attribute_loader
  108. @deferred_scalar_loader.setter
  109. @util.deprecated(
  110. "1.4",
  111. message="The ClassManager.deferred_scalar_loader attribute is now "
  112. "named expired_attribute_loader",
  113. )
  114. def deferred_scalar_loader(self, obj):
  115. self.expired_attribute_loader = obj
  116. def __init__(self, class_):
  117. self.class_ = class_
  118. self.info = {}
  119. self.new_init = None
  120. self.local_attrs = {}
  121. self.originals = {}
  122. self._finalized = False
  123. self.factory = None
  124. self.init_method = None
  125. self._bases = [
  126. mgr
  127. for mgr in cast(
  128. "List[Optional[ClassManager[Any]]]",
  129. [
  130. opt_manager_of_class(base)
  131. for base in self.class_.__bases__
  132. if isinstance(base, type)
  133. ],
  134. )
  135. if mgr is not None
  136. ]
  137. for base_ in self._bases:
  138. self.update(base_)
  139. cast(
  140. "InstanceEvents", self.dispatch._events
  141. )._new_classmanager_instance(class_, self)
  142. for basecls in class_.__mro__:
  143. mgr = opt_manager_of_class(basecls)
  144. if mgr is not None:
  145. self.dispatch._update(mgr.dispatch)
  146. self.manage()
  147. if "__del__" in class_.__dict__:
  148. util.warn(
  149. "__del__() method on class %s will "
  150. "cause unreachable cycles and memory leaks, "
  151. "as SQLAlchemy instrumentation often creates "
  152. "reference cycles. Please remove this method." % class_
  153. )
  154. def _update_state(
  155. self,
  156. finalize: bool = False,
  157. mapper: Optional[Mapper[_O]] = None,
  158. registry: Optional[_RegistryType] = None,
  159. declarative_scan: Optional[_MapperConfig] = None,
  160. expired_attribute_loader: Optional[
  161. _ExpiredAttributeLoaderProto
  162. ] = None,
  163. init_method: Optional[Callable[..., None]] = None,
  164. ) -> None:
  165. if mapper:
  166. self.mapper = mapper #
  167. if registry:
  168. registry._add_manager(self)
  169. if declarative_scan:
  170. self.declarative_scan = weakref.ref(declarative_scan)
  171. if expired_attribute_loader:
  172. self.expired_attribute_loader = expired_attribute_loader
  173. if init_method:
  174. assert not self._finalized, (
  175. "class is already instrumented, "
  176. "init_method %s can't be applied" % init_method
  177. )
  178. self.init_method = init_method
  179. if not self._finalized:
  180. self.original_init = (
  181. self.init_method
  182. if self.init_method is not None
  183. and self.class_.__init__ is object.__init__
  184. else self.class_.__init__
  185. )
  186. if finalize and not self._finalized:
  187. self._finalize()
  188. def _finalize(self) -> None:
  189. if self._finalized:
  190. return
  191. self._finalized = True
  192. self._instrument_init()
  193. _instrumentation_factory.dispatch.class_instrument(self.class_)
  194. def __hash__(self) -> int: # type: ignore[override]
  195. return id(self)
  196. def __eq__(self, other: Any) -> bool:
  197. return other is self
  198. @property
  199. def is_mapped(self) -> bool:
  200. return "mapper" in self.__dict__
  201. @HasMemoized.memoized_attribute
  202. def _all_key_set(self):
  203. return frozenset(self)
  204. @HasMemoized.memoized_attribute
  205. def _collection_impl_keys(self):
  206. return frozenset(
  207. [attr.key for attr in self.values() if attr.impl.collection]
  208. )
  209. @HasMemoized.memoized_attribute
  210. def _scalar_loader_impls(self):
  211. return frozenset(
  212. [
  213. attr.impl
  214. for attr in self.values()
  215. if attr.impl.accepts_scalar_loader
  216. ]
  217. )
  218. @HasMemoized.memoized_attribute
  219. def _loader_impls(self):
  220. return frozenset([attr.impl for attr in self.values()])
  221. @util.memoized_property
  222. def mapper(self) -> Mapper[_O]:
  223. # raises unless self.mapper has been assigned
  224. raise exc.UnmappedClassError(self.class_)
  225. def _all_sqla_attributes(self, exclude=None):
  226. """return an iterator of all classbound attributes that are
  227. implement :class:`.InspectionAttr`.
  228. This includes :class:`.QueryableAttribute` as well as extension
  229. types such as :class:`.hybrid_property` and
  230. :class:`.AssociationProxy`.
  231. """
  232. found: Dict[str, Any] = {}
  233. # constraints:
  234. # 1. yield keys in cls.__dict__ order
  235. # 2. if a subclass has the same key as a superclass, include that
  236. # key as part of the ordering of the superclass, because an
  237. # overridden key is usually installed by the mapper which is going
  238. # on a different ordering
  239. # 3. don't use getattr() as this fires off descriptors
  240. for supercls in self.class_.__mro__[0:-1]:
  241. inherits = supercls.__mro__[1]
  242. for key in supercls.__dict__:
  243. found.setdefault(key, supercls)
  244. if key in inherits.__dict__:
  245. continue
  246. val = found[key].__dict__[key]
  247. if (
  248. isinstance(val, interfaces.InspectionAttr)
  249. and val.is_attribute
  250. ):
  251. yield key, val
  252. def _get_class_attr_mro(self, key, default=None):
  253. """return an attribute on the class without tripping it."""
  254. for supercls in self.class_.__mro__:
  255. if key in supercls.__dict__:
  256. return supercls.__dict__[key]
  257. else:
  258. return default
  259. def _attr_has_impl(self, key: str) -> bool:
  260. """Return True if the given attribute is fully initialized.
  261. i.e. has an impl.
  262. """
  263. return key in self and self[key].impl is not None
  264. def _subclass_manager(self, cls: Type[_T]) -> ClassManager[_T]:
  265. """Create a new ClassManager for a subclass of this ClassManager's
  266. class.
  267. This is called automatically when attributes are instrumented so that
  268. the attributes can be propagated to subclasses against their own
  269. class-local manager, without the need for mappers etc. to have already
  270. pre-configured managers for the full class hierarchy. Mappers
  271. can post-configure the auto-generated ClassManager when needed.
  272. """
  273. return register_class(cls, finalize=False)
  274. def _instrument_init(self):
  275. self.new_init = _generate_init(self.class_, self, self.original_init)
  276. self.install_member("__init__", self.new_init)
  277. @util.memoized_property
  278. def _state_constructor(self) -> Type[state.InstanceState[_O]]:
  279. self.dispatch.first_init(self, self.class_)
  280. return state.InstanceState
  281. def manage(self):
  282. """Mark this instance as the manager for its class."""
  283. setattr(self.class_, self.MANAGER_ATTR, self)
  284. @util.hybridmethod
  285. def manager_getter(self):
  286. return _default_manager_getter
  287. @util.hybridmethod
  288. def state_getter(self):
  289. """Return a (instance) -> InstanceState callable.
  290. "state getter" callables should raise either KeyError or
  291. AttributeError if no InstanceState could be found for the
  292. instance.
  293. """
  294. return _default_state_getter
  295. @util.hybridmethod
  296. def dict_getter(self):
  297. return _default_dict_getter
  298. def instrument_attribute(
  299. self,
  300. key: str,
  301. inst: QueryableAttribute[Any],
  302. propagated: bool = False,
  303. ) -> None:
  304. if propagated:
  305. if key in self.local_attrs:
  306. return # don't override local attr with inherited attr
  307. else:
  308. self.local_attrs[key] = inst
  309. self.install_descriptor(key, inst)
  310. self._reset_memoizations()
  311. self[key] = inst
  312. for cls in self.class_.__subclasses__():
  313. manager = self._subclass_manager(cls)
  314. manager.instrument_attribute(key, inst, True)
  315. def subclass_managers(self, recursive):
  316. for cls in self.class_.__subclasses__():
  317. mgr = opt_manager_of_class(cls)
  318. if mgr is not None and mgr is not self:
  319. yield mgr
  320. if recursive:
  321. yield from mgr.subclass_managers(True)
  322. def post_configure_attribute(self, key):
  323. _instrumentation_factory.dispatch.attribute_instrument(
  324. self.class_, key, self[key]
  325. )
  326. def uninstrument_attribute(self, key, propagated=False):
  327. if key not in self:
  328. return
  329. if propagated:
  330. if key in self.local_attrs:
  331. return # don't get rid of local attr
  332. else:
  333. del self.local_attrs[key]
  334. self.uninstall_descriptor(key)
  335. self._reset_memoizations()
  336. del self[key]
  337. for cls in self.class_.__subclasses__():
  338. manager = opt_manager_of_class(cls)
  339. if manager:
  340. manager.uninstrument_attribute(key, True)
  341. def unregister(self) -> None:
  342. """remove all instrumentation established by this ClassManager."""
  343. for key in list(self.originals):
  344. self.uninstall_member(key)
  345. self.mapper = None
  346. self.dispatch = None # type: ignore
  347. self.new_init = None
  348. self.info.clear()
  349. for key in list(self):
  350. if key in self.local_attrs:
  351. self.uninstrument_attribute(key)
  352. if self.MANAGER_ATTR in self.class_.__dict__:
  353. delattr(self.class_, self.MANAGER_ATTR)
  354. def install_descriptor(
  355. self, key: str, inst: QueryableAttribute[Any]
  356. ) -> None:
  357. if key in (self.STATE_ATTR, self.MANAGER_ATTR):
  358. raise KeyError(
  359. "%r: requested attribute name conflicts with "
  360. "instrumentation attribute of the same name." % key
  361. )
  362. setattr(self.class_, key, inst)
  363. def uninstall_descriptor(self, key: str) -> None:
  364. delattr(self.class_, key)
  365. def install_member(self, key: str, implementation: Any) -> None:
  366. if key in (self.STATE_ATTR, self.MANAGER_ATTR):
  367. raise KeyError(
  368. "%r: requested attribute name conflicts with "
  369. "instrumentation attribute of the same name." % key
  370. )
  371. self.originals.setdefault(key, self.class_.__dict__.get(key, DEL_ATTR))
  372. setattr(self.class_, key, implementation)
  373. def uninstall_member(self, key: str) -> None:
  374. original = self.originals.pop(key, None)
  375. if original is not DEL_ATTR:
  376. setattr(self.class_, key, original)
  377. else:
  378. delattr(self.class_, key)
  379. def instrument_collection_class(
  380. self, key: str, collection_class: Type[Collection[Any]]
  381. ) -> _CollectionFactoryType:
  382. return collections.prepare_instrumentation(collection_class)
  383. def initialize_collection(
  384. self,
  385. key: str,
  386. state: InstanceState[_O],
  387. factory: _CollectionFactoryType,
  388. ) -> Tuple[collections.CollectionAdapter, _AdaptedCollectionProtocol]:
  389. user_data = factory()
  390. impl = self.get_impl(key)
  391. assert _is_collection_attribute_impl(impl)
  392. adapter = collections.CollectionAdapter(impl, state, user_data)
  393. return adapter, user_data
  394. def is_instrumented(self, key: str, search: bool = False) -> bool:
  395. if search:
  396. return key in self
  397. else:
  398. return key in self.local_attrs
  399. def get_impl(self, key: str) -> AttributeImpl:
  400. return self[key].impl
  401. @property
  402. def attributes(self) -> Iterable[Any]:
  403. return iter(self.values())
  404. # InstanceState management
  405. def new_instance(self, state: Optional[InstanceState[_O]] = None) -> _O:
  406. # here, we would prefer _O to be bound to "object"
  407. # so that mypy sees that __new__ is present. currently
  408. # it's bound to Any as there were other problems not having
  409. # it that way but these can be revisited
  410. instance = self.class_.__new__(self.class_)
  411. if state is None:
  412. state = self._state_constructor(instance, self)
  413. self._state_setter(instance, state)
  414. return instance
  415. def setup_instance(
  416. self, instance: _O, state: Optional[InstanceState[_O]] = None
  417. ) -> None:
  418. if state is None:
  419. state = self._state_constructor(instance, self)
  420. self._state_setter(instance, state)
  421. def teardown_instance(self, instance: _O) -> None:
  422. delattr(instance, self.STATE_ATTR)
  423. def _serialize(
  424. self, state: InstanceState[_O], state_dict: Dict[str, Any]
  425. ) -> _SerializeManager:
  426. return _SerializeManager(state, state_dict)
  427. def _new_state_if_none(
  428. self, instance: _O
  429. ) -> Union[Literal[False], InstanceState[_O]]:
  430. """Install a default InstanceState if none is present.
  431. A private convenience method used by the __init__ decorator.
  432. """
  433. if hasattr(instance, self.STATE_ATTR):
  434. return False
  435. elif self.class_ is not instance.__class__ and self.is_mapped:
  436. # this will create a new ClassManager for the
  437. # subclass, without a mapper. This is likely a
  438. # user error situation but allow the object
  439. # to be constructed, so that it is usable
  440. # in a non-ORM context at least.
  441. return self._subclass_manager(
  442. instance.__class__
  443. )._new_state_if_none(instance)
  444. else:
  445. state = self._state_constructor(instance, self)
  446. self._state_setter(instance, state)
  447. return state
  448. def has_state(self, instance: _O) -> bool:
  449. return hasattr(instance, self.STATE_ATTR)
  450. def has_parent(
  451. self, state: InstanceState[_O], key: str, optimistic: bool = False
  452. ) -> bool:
  453. """TODO"""
  454. return self.get_impl(key).hasparent(state, optimistic=optimistic)
  455. def __bool__(self) -> bool:
  456. """All ClassManagers are non-zero regardless of attribute state."""
  457. return True
  458. def __repr__(self) -> str:
  459. return "<%s of %r at %x>" % (
  460. self.__class__.__name__,
  461. self.class_,
  462. id(self),
  463. )
  464. class _SerializeManager:
  465. """Provide serialization of a :class:`.ClassManager`.
  466. The :class:`.InstanceState` uses ``__init__()`` on serialize
  467. and ``__call__()`` on deserialize.
  468. """
  469. def __init__(self, state: state.InstanceState[Any], d: Dict[str, Any]):
  470. self.class_ = state.class_
  471. manager = state.manager
  472. manager.dispatch.pickle(state, d)
  473. def __call__(self, state, inst, state_dict):
  474. state.manager = manager = opt_manager_of_class(self.class_)
  475. if manager is None:
  476. raise exc.UnmappedInstanceError(
  477. inst,
  478. "Cannot deserialize object of type %r - "
  479. "no mapper() has "
  480. "been configured for this class within the current "
  481. "Python process!" % self.class_,
  482. )
  483. elif manager.is_mapped and not manager.mapper.configured:
  484. manager.mapper._check_configure()
  485. # setup _sa_instance_state ahead of time so that
  486. # unpickle events can access the object normally.
  487. # see [ticket:2362]
  488. if inst is not None:
  489. manager.setup_instance(inst, state)
  490. manager.dispatch.unpickle(state, state_dict)
  491. class InstrumentationFactory(EventTarget):
  492. """Factory for new ClassManager instances."""
  493. dispatch: dispatcher[InstrumentationFactory]
  494. def create_manager_for_cls(self, class_: Type[_O]) -> ClassManager[_O]:
  495. assert class_ is not None
  496. assert opt_manager_of_class(class_) is None
  497. # give a more complicated subclass
  498. # a chance to do what it wants here
  499. manager, factory = self._locate_extended_factory(class_)
  500. if factory is None:
  501. factory = ClassManager
  502. manager = ClassManager(class_)
  503. else:
  504. assert manager is not None
  505. self._check_conflicts(class_, factory)
  506. manager.factory = factory
  507. return manager
  508. def _locate_extended_factory(
  509. self, class_: Type[_O]
  510. ) -> Tuple[Optional[ClassManager[_O]], Optional[_ManagerFactory]]:
  511. """Overridden by a subclass to do an extended lookup."""
  512. return None, None
  513. def _check_conflicts(
  514. self, class_: Type[_O], factory: Callable[[Type[_O]], ClassManager[_O]]
  515. ) -> None:
  516. """Overridden by a subclass to test for conflicting factories."""
  517. def unregister(self, class_: Type[_O]) -> None:
  518. manager = manager_of_class(class_)
  519. manager.unregister()
  520. self.dispatch.class_uninstrument(class_)
  521. # this attribute is replaced by sqlalchemy.ext.instrumentation
  522. # when imported.
  523. _instrumentation_factory = InstrumentationFactory()
  524. # these attributes are replaced by sqlalchemy.ext.instrumentation
  525. # when a non-standard InstrumentationManager class is first
  526. # used to instrument a class.
  527. instance_state = _default_state_getter = base.instance_state
  528. instance_dict = _default_dict_getter = base.instance_dict
  529. manager_of_class = _default_manager_getter = base.manager_of_class
  530. opt_manager_of_class = _default_opt_manager_getter = base.opt_manager_of_class
  531. def register_class(
  532. class_: Type[_O],
  533. finalize: bool = True,
  534. mapper: Optional[Mapper[_O]] = None,
  535. registry: Optional[_RegistryType] = None,
  536. declarative_scan: Optional[_MapperConfig] = None,
  537. expired_attribute_loader: Optional[_ExpiredAttributeLoaderProto] = None,
  538. init_method: Optional[Callable[..., None]] = None,
  539. ) -> ClassManager[_O]:
  540. """Register class instrumentation.
  541. Returns the existing or newly created class manager.
  542. """
  543. manager = opt_manager_of_class(class_)
  544. if manager is None:
  545. manager = _instrumentation_factory.create_manager_for_cls(class_)
  546. manager._update_state(
  547. mapper=mapper,
  548. registry=registry,
  549. declarative_scan=declarative_scan,
  550. expired_attribute_loader=expired_attribute_loader,
  551. init_method=init_method,
  552. finalize=finalize,
  553. )
  554. return manager
  555. def unregister_class(class_):
  556. """Unregister class instrumentation."""
  557. _instrumentation_factory.unregister(class_)
  558. def is_instrumented(instance, key):
  559. """Return True if the given attribute on the given instance is
  560. instrumented by the attributes package.
  561. This function may be used regardless of instrumentation
  562. applied directly to the class, i.e. no descriptors are required.
  563. """
  564. return manager_of_class(instance.__class__).is_instrumented(
  565. key, search=True
  566. )
  567. def _generate_init(class_, class_manager, original_init):
  568. """Build an __init__ decorator that triggers ClassManager events."""
  569. # TODO: we should use the ClassManager's notion of the
  570. # original '__init__' method, once ClassManager is fixed
  571. # to always reference that.
  572. if original_init is None:
  573. original_init = class_.__init__
  574. # Go through some effort here and don't change the user's __init__
  575. # calling signature, including the unlikely case that it has
  576. # a return value.
  577. # FIXME: need to juggle local names to avoid constructor argument
  578. # clashes.
  579. func_body = """\
  580. def __init__(%(apply_pos)s):
  581. new_state = class_manager._new_state_if_none(%(self_arg)s)
  582. if new_state:
  583. return new_state._initialize_instance(%(apply_kw)s)
  584. else:
  585. return original_init(%(apply_kw)s)
  586. """
  587. func_vars = util.format_argspec_init(original_init, grouped=False)
  588. func_text = func_body % func_vars
  589. func_defaults = getattr(original_init, "__defaults__", None)
  590. func_kw_defaults = getattr(original_init, "__kwdefaults__", None)
  591. env = locals().copy()
  592. env["__name__"] = __name__
  593. exec(func_text, env)
  594. __init__ = env["__init__"]
  595. __init__.__doc__ = original_init.__doc__
  596. __init__._sa_original_init = original_init
  597. if func_defaults:
  598. __init__.__defaults__ = func_defaults
  599. if func_kw_defaults:
  600. __init__.__kwdefaults__ = func_kw_defaults
  601. return __init__