Participer au site avec un Tip
Rechercher
 

Améliorations / Corrections

Vous avez des améliorations (ou des corrections) à proposer pour ce document : je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.

Emplacement :

Description des améliorations :

Vous êtes un professionnel et vous avez besoin d'une formation ? Machine Learning
avec Scikit-Learn
Voir le programme détaillé
Module « sqlalchemy.orm »

Classe « declared_attr »

Informations générales

Héritage

    builtins.object
        _declared_attr_common
builtins.object
    TypingOnly
builtins.object
    Generic
        _MappedAttribute
            declared_attr

Définition

class declared_attr(_MappedAttribute, _declared_attr_common):

help(declared_attr)

Mark a class-level method as representing the definition of
a mapped property or Declarative directive.

:class:`_orm.declared_attr` is typically applied as a decorator to a class
level method, turning the attribute into a scalar-like property that can be
invoked from the uninstantiated class. The Declarative mapping process
looks for these :class:`_orm.declared_attr` callables as it scans classes,
and assumes any attribute marked with :class:`_orm.declared_attr` will be a
callable that will produce an object specific to the Declarative mapping or
table configuration.

:class:`_orm.declared_attr` is usually applicable to
:ref:`mixins <orm_mixins_toplevel>`, to define relationships that are to be
applied to different implementors of the class. It may also be used to
define dynamically generated column expressions and other Declarative
attributes.

Example::

    class ProvidesUserMixin:
        "A mixin that adds a 'user' relationship to classes."

        user_id: Mapped[int] = mapped_column(ForeignKey("user_table.id"))

        @declared_attr
        def user(cls) -> Mapped["User"]:
            return relationship("User")

When used with Declarative directives such as ``__tablename__``, the
:meth:`_orm.declared_attr.directive` modifier may be used which indicates
to :pep:`484` typing tools that the given method is not dealing with
:class:`_orm.Mapped` attributes::

    class CreateTableName:
        @declared_attr.directive
        def __tablename__(cls) -> str:
            return cls.__name__.lower()

:class:`_orm.declared_attr` can also be applied directly to mapped
classes, to allow for attributes that dynamically configure themselves
on subclasses when using mapped inheritance schemes.   Below
illustrates :class:`_orm.declared_attr` to create a dynamic scheme
for generating the :paramref:`_orm.Mapper.polymorphic_identity` parameter
for subclasses::

    class Employee(Base):
        __tablename__ = "employee"

        id: Mapped[int] = mapped_column(primary_key=True)
        type: Mapped[str] = mapped_column(String(50))

        @declared_attr.directive
        def __mapper_args__(cls) -> Dict[str, Any]:
            if cls.__name__ == "Employee":
                return {
                    "polymorphic_on": cls.type,
                    "polymorphic_identity": "Employee",
                }
            else:
                return {"polymorphic_identity": cls.__name__}


    class Engineer(Employee):
        pass

:class:`_orm.declared_attr` supports decorating functions that are
explicitly decorated with ``@classmethod``. This is never necessary from a
runtime perspective, however may be needed in order to support :pep:`484`
typing tools that don't otherwise recognize the decorated function as
having class-level behaviors for the ``cls`` parameter::

    class SomethingMixin:
        x: Mapped[int]
        y: Mapped[int]

        @declared_attr
        @classmethod
        def x_plus_y(cls) -> Mapped[int]:
            return column_property(cls.x + cls.y)

.. versionadded:: 2.0 - :class:`_orm.declared_attr` can accommodate a
   function decorated with ``@classmethod`` to help with :pep:`484`
   integration where needed.


.. seealso::

    :ref:`orm_mixins_toplevel` - Declarative Mixin documentation with
    background on use patterns for :class:`_orm.declared_attr`.

Constructeur(s)

Signature du constructeur Description
__init__(self, fn: 'Callable[..., Any]', cascading: 'bool' = False, quiet: 'bool' = False)

Liste des opérateurs

Opérateurs hérités de la classe object

__eq__, __ge__, __gt__, __le__, __lt__, __ne__

Liste des méthodes

Toutes les méthodes Méthodes d'instance Méthodes statiques Méthodes dépréciées
Signature de la méthodeDescription
__class_getitem__ Parameterizes a generic class. [extrait de __class_getitem__.__doc__]
cascading

Méthodes héritées de la classe _declared_attr_common

__get__, __init_subclass__, __subclasshook__

Méthodes héritées de la classe object

__delattr__, __dir__, __format__, __getattribute__, __getstate__, __hash__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__

Vous êtes un professionnel et vous avez besoin d'une formation ? Calcul scientifique
avec Python
Voir le programme détaillé