instrumentation.py 24 KB

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