1.. module:: sqlalchemy.orm
2
3.. _mapping_constructors:
4
5Constructors and Object Initialization
6=======================================
7
8Mapping imposes no restrictions or requirements on the constructor
9(``__init__``) method for the class. You are free to require any arguments for
10the function that you wish, assign attributes to the instance that are unknown
11to the ORM, and generally do anything else you would normally do when writing
12a constructor for a Python class.
13
14The SQLAlchemy ORM does not call ``__init__`` when recreating objects from
15database rows. The ORM's process is somewhat akin to the Python standard
16library's ``pickle`` module, invoking the low level ``__new__`` method and
17then quietly restoring attributes directly on the instance rather than calling
18``__init__``.
19
20If you need to do some setup on database-loaded instances before they're ready
21to use, you can use the ``@reconstructor`` decorator to tag a method as the
22ORM counterpart to ``__init__``. SQLAlchemy will call this method with no
23arguments every time it loads or reconstructs one of your instances. This is
24useful for recreating transient properties that are normally assigned in your
25``__init__``::
26
27    from sqlalchemy import orm
28
29    class MyMappedClass(object):
30        def __init__(self, data):
31            self.data = data
32            # we need stuff on all instances, but not in the database.
33            self.stuff = []
34
35        @orm.reconstructor
36        def init_on_load(self):
37            self.stuff = []
38
39When ``obj = MyMappedClass()`` is executed, Python calls the ``__init__``
40method as normal and the ``data`` argument is required.  When instances are
41loaded during a :class:`~sqlalchemy.orm.query.Query` operation as in
42``query(MyMappedClass).one()``, ``init_on_load`` is called.
43
44Any method may be tagged as the :func:`~sqlalchemy.orm.reconstructor`, even
45the ``__init__`` method. SQLAlchemy will call the reconstructor method with no
46arguments. Scalar (non-collection) database-mapped attributes of the instance
47will be available for use within the function. Eagerly-loaded collections are
48generally not yet available and will usually only contain the first element.
49ORM state changes made to objects at this stage will not be recorded for the
50next flush() operation, so the activity within a reconstructor should be
51conservative.
52
53:func:`~sqlalchemy.orm.reconstructor` is a shortcut into a larger system
54of "instance level" events, which can be subscribed to using the
55event API - see :class:`.InstanceEvents` for the full API description
56of these events.
57
58.. autofunction:: reconstructor
59