<commit_before>"""Contain the ``AssociationProxy`` class.

The ``AssociationProxy`` is a Python property object which provides
transparent proxied access to the endpoint of an association object.

See the example ``examples/association/proxied_association.py``.
"""

import weakref, itertools
import sqlalchemy.exceptions as exceptions
import sqlalchemy.orm as orm
import sqlalchemy.util as util


def association_proxy(targetcollection, attr, **kw):
    """Convenience function for use in mapped classes.  Implements a Python
    property representing a relation as a collection of simpler values.  The
    proxied property will mimic the collection type of the target (list, dict
    or set), or in the case of a one to one relation, a simple scalar value.

    targetcollection
      Name of the relation attribute we'll proxy to, usually created with
      'relation()' in a mapper setup.

    attr
      Attribute on the associated instances we'll proxy for.  For example,
      given a target collection of [obj1, obj2], a list created by this proxy
      property would look like
      [getattr(obj1, attr), getattr(obj2, attr)]

      If the relation is one-to-one or otherwise uselist=False, then simply:
      getattr(obj, attr)

    creator (optional)
      When new items are added to this proxied collection, new instances of
      the class collected by the target collection will be created.  For
      list and set collections, the target class constructor will be called
      with the 'value' for the new instance.  For dict types, two arguments
      are passed: key and value.

      If you want to construct instances differently, supply a 'creator'
      function that takes arguments as above and returns instances.

      For scalar relations, creator() will be called if the target is None.
      If the target is present, set operations are proxied to setattr() on the
      associated object.

      If you have an associated object with multiple attributes, you may set up
      multiple association proxies mapping to different attributes.  See the
      unit tests for examples, and for examples of how creator() functions can
      be used to construct the scalar relation on-demand in this situation.

    Passes along any other arguments to AssociationProxy
    """

    return AssociationProxy(targetcollection, attr, **kw)


class AssociationProxy(object):
    """A property object that automatically sets up `AssociationLists`
    on an object."""

    def __init__(self, targetcollection, attr, creator=None,
                 getset_factory=None, proxy_factory=None, proxy_bulk_set=None):
        """Arguments are:

          targetcollection
            Name of the collection we'll proxy to, usually created with
            'relation()' in a mapper setup.

          attr
            Attribute on the collected instances we'll proxy for.  For example,
            given a target collection of [obj1, obj2],
            a list created by this proxy property would look like
            [getattr(obj1, attr), getattr(obj2, attr)]

          creator
            Optional. When new items are added to this proxied collection, new
            instances of the class collected by the target collection will be
            created.  For list and set collections, the target class
            constructor will be called with the 'value' for the new instance.
            For dict types, two arguments are passed: key and value.

            If you want to construct instances differently, supply a 'creator'
            function that takes arguments as above and returns instances.

          getset_factory
            Optional.  Proxied attribute access is automatically handled
            by routines that get and set values based on the `attr` argument
            for this proxy.

            If you would like to customize this behavior, you may supply a
            `getset_factory` callable that produces a tuple of `getter` and
            `setter` functions.  The factory is called with two arguments,
            the abstract type of the underlying collection and this proxy
            instance.

          proxy_factory
            Optional.  The type of collection to emulate is determined by
            sniffing the target collection.  If your collection type can't be
            determined by duck typing or you'd like to use a different collection
            implementation, you may supply a factory function to produce those
            collections.  Only applicable to non-scalar relations.

          proxy_bulk_set
            Optional, use with proxy_factory.  See the _set() method for
            details.
        """
        
        self.target_collection = targetcollection # backwards compat name...
        self.value_attr = attr
        self.creator = creator
        self.getset_factory = getset_factory
        self.proxy_factory = proxy_factory
        self.proxy_bulk_set = proxy_bulk_set

        self.scalar = None
        self.owning_class = None
        self.key = '_%s_%s_%s' % (type(self).__name__,
                                  targetcollection, id(self))
        self.collection_class = None

    def _get_property(self):
        return orm.class_mapper(self.owning_class).get_property(self.target_collection)

    def _target_class(self):
        return self._get_property().mapper.class_
    target_class = property(_target_class)

    def _target_is_scalar(self):
        return not self._get_property().uselist

    def _lazy_collection(self, weakobjref):
        target = self.target_collection
        del self
        def lazy_collection():
            obj = weakobjref()
            if obj is None:
                raise exceptions.InvalidRequestError(
                    "stale association proxy, parent object has gone out of "
                    "scope")
            return getattr(obj, target)
        return lazy_collection
        
    def __get__(self, obj, class_):
        if obj is None:
            self.owning_class = class_
            return
        elif self.scalar is None:
            self.scalar = self._target_is_scalar()

        if self.scalar:
            return getattr(getattr(obj, self.target_collection), self.value_attr)
        else:
            try:
                return getattr(obj, self.key)
            except AttributeError:
                proxy = self._new(self._lazy_collection(weakref.ref(obj)))
                setattr(obj, self.key, proxy)
                return proxy

    def __set__(self, obj, values):
        if self.scalar is None:
            self.scalar = self._target_is_scalar()

        if self.scalar:
            creator = self.creator and self.creator or self.target_class
            target = getattr(obj, self.target_collection)
            if target is None:
                setattr(obj, self.target_collection, creator(values))
            else:
                setattr(target, self.value_attr, values)
        else:
            proxy = self.__get__(obj, None)
            proxy.clear()
            self._set(proxy, values)

    def __delete__(self, obj):
        delattr(obj, self.key)

    def _default_getset(self, collection_class):
        attr = self.value_attr
        getter = util.attrgetter(attr)
        if collection_class is dict:<commit_msg>Expand custom assocproxy getter/setter support to scalar proxies<commit_after>"""Contain the ``AssociationProxy`` class.

The ``AssociationProxy`` is a Python property object which provides
transparent proxied access to the endpoint of an association object.

See the example ``examples/association/proxied_association.py``.
"""

import weakref, itertools
import sqlalchemy.exceptions as exceptions
import sqlalchemy.orm as orm
import sqlalchemy.util as util


def association_proxy(targetcollection, attr, **kw):
    """Convenience function for use in mapped classes.  Implements a Python
    property representing a relation as a collection of simpler values.  The
    proxied property will mimic the collection type of the target (list, dict
    or set), or in the case of a one to one relation, a simple scalar value.

    targetcollection
      Name of the relation attribute we'll proxy to, usually created with
      'relation()' in a mapper setup.

    attr
      Attribute on the associated instances we'll proxy for.  For example,
      given a target collection of [obj1, obj2], a list created by this proxy
      property would look like
      [getattr(obj1, attr), getattr(obj2, attr)]

      If the relation is one-to-one or otherwise uselist=False, then simply:
      getattr(obj, attr)

    creator (optional)
      When new items are added to this proxied collection, new instances of
      the class collected by the target collection will be created.  For
      list and set collections, the target class constructor will be called
      with the 'value' for the new instance.  For dict types, two arguments
      are passed: key and value.

      If you want to construct instances differently, supply a 'creator'
      function that takes arguments as above and returns instances.

      For scalar relations, creator() will be called if the target is None.
      If the target is present, set operations are proxied to setattr() on the
      associated object.

      If you have an associated object with multiple attributes, you may set up
      multiple association proxies mapping to different attributes.  See the
      unit tests for examples, and for examples of how creator() functions can
      be used to construct the scalar relation on-demand in this situation.

    Passes along any other arguments to AssociationProxy
    """

    return AssociationProxy(targetcollection, attr, **kw)


class AssociationProxy(object):
    """A property object that automatically sets up `AssociationLists`
    on an object."""

    def __init__(self, targetcollection, attr, creator=None,
                 getset_factory=None, proxy_factory=None, proxy_bulk_set=None):
        """Arguments are:

          targetcollection
            Name of the collection we'll proxy to, usually created with
            'relation()' in a mapper setup.

          attr
            Attribute on the collected instances we'll proxy for.  For example,
            given a target collection of [obj1, obj2],
            a list created by this proxy property would look like
            [getattr(obj1, attr), getattr(obj2, attr)]

          creator
            Optional. When new items are added to this proxied collection, new
            instances of the class collected by the target collection will be
            created.  For list and set collections, the target class
            constructor will be called with the 'value' for the new instance.
            For dict types, two arguments are passed: key and value.

            If you want to construct instances differently, supply a 'creator'
            function that takes arguments as above and returns instances.

          getset_factory
            Optional.  Proxied attribute access is automatically handled
            by routines that get and set values based on the `attr` argument
            for this proxy.

            If you would like to customize this behavior, you may supply a
            `getset_factory` callable that produces a tuple of `getter` and
            `setter` functions.  The factory is called with two arguments,
            the abstract type of the underlying collection and this proxy
            instance.

          proxy_factory
            Optional.  The type of collection to emulate is determined by
            sniffing the target collection.  If your collection type can't be
            determined by duck typing or you'd like to use a different collection
            implementation, you may supply a factory function to produce those
            collections.  Only applicable to non-scalar relations.

          proxy_bulk_set
            Optional, use with proxy_factory.  See the _set() method for
            details.
        """
        
        self.target_collection = targetcollection # backwards compat name...
        self.value_attr = attr
        self.creator = creator
        self.getset_factory = getset_factory
        self.proxy_factory = proxy_factory
        self.proxy_bulk_set = proxy_bulk_set

        self.scalar = None
        self.owning_class = None
        self.key = '_%s_%s_%s' % (type(self).__name__,
                                  targetcollection, id(self))
        self.collection_class = None

    def _get_property(self):
        return orm.class_mapper(self.owning_class).get_property(self.target_collection)

    def _target_class(self):
        return self._get_property().mapper.class_
    target_class = property(_target_class)

    def _target_is_scalar(self):
        return not self._get_property().uselist

    def _lazy_collection(self, weakobjref):
        target = self.target_collection
        del self
        def lazy_collection():
            obj = weakobjref()
            if obj is None:
                raise exceptions.InvalidRequestError(
                    "stale association proxy, parent object has gone out of "
                    "scope")
            return getattr(obj, target)
        return lazy_collection
        
    def __get__(self, obj, class_):
        if obj is None:
            self.owning_class = class_
            return
        elif self.scalar is None:
            self.scalar = self._target_is_scalar()
            if self.scalar:
                self._initialize_scalar_accessors()

        if self.scalar:
            return self._scalar_get(getattr(obj, self.target_collection))
        else:
            try:
                return getattr(obj, self.key)
            except AttributeError:
                proxy = self._new(self._lazy_collection(weakref.ref(obj)))
                setattr(obj, self.key, proxy)
                return proxy

    def __set__(self, obj, values):
        if self.scalar is None:
            self.scalar = self._target_is_scalar()
            if self.scalar:
                self._initialize_scalar_accessors()

        if self.scalar:
            creator = self.creator and self.creator or self.target_class
            target = getattr(obj, self.target_collection)
            if target is None:
                setattr(obj, self.target_collection, creator(values))
            else:
                self._scalar_set(target, values)
        else:
            proxy = self.__get__(obj, None)
            proxy.clear()
            self._set(proxy, values)

    def __delete__(self, obj):
        delattr(obj, self.key)

    def _initialize_scalar_accessors(self):
        if self.getset_factory:
            get, set = self.getset_factory(None, self)
        else:
            get, set = self._default_getset(None)
        self._scalar_get, self._scalar_set = get, set

    def _default_getset(self, collection_class):
        attr = self.value_attr
        getter = util.attrgetter(attr)
        if collection_class is dict:
{'fraction_non_alphanumeric': 0.05824533439596201, 'fraction_numerical': 0.0010626286776914391, 'mean_word_length': 2.3138204225352115, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7234141', 'n_tokens_mistral': 3756, 'n_tokens_neox': 3634, 'n_words': 1512}