associationproxy.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611
  1. # ext/associationproxy.py
  2. # Copyright (C) 2005-2022 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. """Contain the ``AssociationProxy`` class.
  8. The ``AssociationProxy`` is a Python property object which provides
  9. transparent proxied access to the endpoint of an association object.
  10. See the example ``examples/association/proxied_association.py``.
  11. """
  12. import operator
  13. from .. import exc
  14. from .. import inspect
  15. from .. import orm
  16. from .. import util
  17. from ..orm import collections
  18. from ..orm import interfaces
  19. from ..sql import or_
  20. from ..sql.operators import ColumnOperators
  21. def association_proxy(target_collection, attr, **kw):
  22. r"""Return a Python property implementing a view of a target
  23. attribute which references an attribute on members of the
  24. target.
  25. The returned value is an instance of :class:`.AssociationProxy`.
  26. Implements a Python property representing a relationship as a collection
  27. of simpler values, or a scalar value. The proxied property will mimic
  28. the collection type of the target (list, dict or set), or, in the case of
  29. a one to one relationship, a simple scalar value.
  30. :param target_collection: Name of the attribute we'll proxy to.
  31. This attribute is typically mapped by
  32. :func:`~sqlalchemy.orm.relationship` to link to a target collection, but
  33. can also be a many-to-one or non-scalar relationship.
  34. :param attr: Attribute on the associated instance or instances we'll
  35. proxy for.
  36. For example, given a target collection of [obj1, obj2], a list created
  37. by this proxy property would look like [getattr(obj1, *attr*),
  38. getattr(obj2, *attr*)]
  39. If the relationship is one-to-one or otherwise uselist=False, then
  40. simply: getattr(obj, *attr*)
  41. :param creator: optional.
  42. When new items are added to this proxied collection, new instances of
  43. the class collected by the target collection will be created. For list
  44. and set collections, the target class constructor will be called with
  45. the 'value' for the new instance. For dict types, two arguments are
  46. passed: key and value.
  47. If you want to construct instances differently, supply a *creator*
  48. function that takes arguments as above and returns instances.
  49. For scalar relationships, creator() will be called if the target is None.
  50. If the target is present, set operations are proxied to setattr() on the
  51. associated object.
  52. If you have an associated object with multiple attributes, you may set
  53. up multiple association proxies mapping to different attributes. See
  54. the unit tests for examples, and for examples of how creator() functions
  55. can be used to construct the scalar relationship on-demand in this
  56. situation.
  57. :param \*\*kw: Passes along any other keyword arguments to
  58. :class:`.AssociationProxy`.
  59. """
  60. return AssociationProxy(target_collection, attr, **kw)
  61. ASSOCIATION_PROXY = util.symbol("ASSOCIATION_PROXY")
  62. """Symbol indicating an :class:`.InspectionAttr` that's
  63. of type :class:`.AssociationProxy`.
  64. Is assigned to the :attr:`.InspectionAttr.extension_type`
  65. attribute.
  66. """
  67. class AssociationProxy(interfaces.InspectionAttrInfo):
  68. """A descriptor that presents a read/write view of an object attribute."""
  69. is_attribute = True
  70. extension_type = ASSOCIATION_PROXY
  71. def __init__(
  72. self,
  73. target_collection,
  74. attr,
  75. creator=None,
  76. getset_factory=None,
  77. proxy_factory=None,
  78. proxy_bulk_set=None,
  79. info=None,
  80. cascade_scalar_deletes=False,
  81. ):
  82. """Construct a new :class:`.AssociationProxy`.
  83. The :func:`.association_proxy` function is provided as the usual
  84. entrypoint here, though :class:`.AssociationProxy` can be instantiated
  85. and/or subclassed directly.
  86. :param target_collection: Name of the collection we'll proxy to,
  87. usually created with :func:`_orm.relationship`.
  88. :param attr: Attribute on the collected instances we'll proxy
  89. for. For example, given a target collection of [obj1, obj2], a
  90. list created by this proxy property would look like
  91. [getattr(obj1, attr), getattr(obj2, attr)]
  92. :param creator: Optional. When new items are added to this proxied
  93. collection, new instances of the class collected by the target
  94. collection will be created. For list and set collections, the
  95. target class constructor will be called with the 'value' for the
  96. new instance. For dict types, two arguments are passed:
  97. key and value.
  98. If you want to construct instances differently, supply a 'creator'
  99. function that takes arguments as above and returns instances.
  100. :param cascade_scalar_deletes: when True, indicates that setting
  101. the proxied value to ``None``, or deleting it via ``del``, should
  102. also remove the source object. Only applies to scalar attributes.
  103. Normally, removing the proxied target will not remove the proxy
  104. source, as this object may have other state that is still to be
  105. kept.
  106. .. versionadded:: 1.3
  107. .. seealso::
  108. :ref:`cascade_scalar_deletes` - complete usage example
  109. :param getset_factory: Optional. Proxied attribute access is
  110. automatically handled by routines that get and set values based on
  111. the `attr` argument for this proxy.
  112. If you would like to customize this behavior, you may supply a
  113. `getset_factory` callable that produces a tuple of `getter` and
  114. `setter` functions. The factory is called with two arguments, the
  115. abstract type of the underlying collection and this proxy instance.
  116. :param proxy_factory: Optional. The type of collection to emulate is
  117. determined by sniffing the target collection. If your collection
  118. type can't be determined by duck typing or you'd like to use a
  119. different collection implementation, you may supply a factory
  120. function to produce those collections. Only applicable to
  121. non-scalar relationships.
  122. :param proxy_bulk_set: Optional, use with proxy_factory. See
  123. the _set() method for details.
  124. :param info: optional, will be assigned to
  125. :attr:`.AssociationProxy.info` if present.
  126. .. versionadded:: 1.0.9
  127. """
  128. self.target_collection = target_collection
  129. self.value_attr = attr
  130. self.creator = creator
  131. self.getset_factory = getset_factory
  132. self.proxy_factory = proxy_factory
  133. self.proxy_bulk_set = proxy_bulk_set
  134. self.cascade_scalar_deletes = cascade_scalar_deletes
  135. self.key = "_%s_%s_%s" % (
  136. type(self).__name__,
  137. target_collection,
  138. id(self),
  139. )
  140. if info:
  141. self.info = info
  142. def __get__(self, obj, class_):
  143. if class_ is None:
  144. return self
  145. inst = self._as_instance(class_, obj)
  146. if inst:
  147. return inst.get(obj)
  148. # obj has to be None here
  149. # assert obj is None
  150. return self
  151. def __set__(self, obj, values):
  152. class_ = type(obj)
  153. return self._as_instance(class_, obj).set(obj, values)
  154. def __delete__(self, obj):
  155. class_ = type(obj)
  156. return self._as_instance(class_, obj).delete(obj)
  157. def for_class(self, class_, obj=None):
  158. r"""Return the internal state local to a specific mapped class.
  159. E.g., given a class ``User``::
  160. class User(Base):
  161. # ...
  162. keywords = association_proxy('kws', 'keyword')
  163. If we access this :class:`.AssociationProxy` from
  164. :attr:`_orm.Mapper.all_orm_descriptors`, and we want to view the
  165. target class for this proxy as mapped by ``User``::
  166. inspect(User).all_orm_descriptors["keywords"].for_class(User).target_class
  167. This returns an instance of :class:`.AssociationProxyInstance` that
  168. is specific to the ``User`` class. The :class:`.AssociationProxy`
  169. object remains agnostic of its parent class.
  170. :param class\_: the class that we are returning state for.
  171. :param obj: optional, an instance of the class that is required
  172. if the attribute refers to a polymorphic target, e.g. where we have
  173. to look at the type of the actual destination object to get the
  174. complete path.
  175. .. versionadded:: 1.3 - :class:`.AssociationProxy` no longer stores
  176. any state specific to a particular parent class; the state is now
  177. stored in per-class :class:`.AssociationProxyInstance` objects.
  178. """
  179. return self._as_instance(class_, obj)
  180. def _as_instance(self, class_, obj):
  181. try:
  182. inst = class_.__dict__[self.key + "_inst"]
  183. except KeyError:
  184. inst = None
  185. # avoid exception context
  186. if inst is None:
  187. owner = self._calc_owner(class_)
  188. if owner is not None:
  189. inst = AssociationProxyInstance.for_proxy(self, owner, obj)
  190. setattr(class_, self.key + "_inst", inst)
  191. else:
  192. inst = None
  193. if inst is not None and not inst._is_canonical:
  194. # the AssociationProxyInstance can't be generalized
  195. # since the proxied attribute is not on the targeted
  196. # class, only on subclasses of it, which might be
  197. # different. only return for the specific
  198. # object's current value
  199. return inst._non_canonical_get_for_object(obj)
  200. else:
  201. return inst
  202. def _calc_owner(self, target_cls):
  203. # we might be getting invoked for a subclass
  204. # that is not mapped yet, in some declarative situations.
  205. # save until we are mapped
  206. try:
  207. insp = inspect(target_cls)
  208. except exc.NoInspectionAvailable:
  209. # can't find a mapper, don't set owner. if we are a not-yet-mapped
  210. # subclass, we can also scan through __mro__ to find a mapped
  211. # class, but instead just wait for us to be called again against a
  212. # mapped class normally.
  213. return None
  214. else:
  215. return insp.mapper.class_manager.class_
  216. def _default_getset(self, collection_class):
  217. attr = self.value_attr
  218. _getter = operator.attrgetter(attr)
  219. def getter(target):
  220. return _getter(target) if target is not None else None
  221. if collection_class is dict:
  222. def setter(o, k, v):
  223. setattr(o, attr, v)
  224. else:
  225. def setter(o, v):
  226. setattr(o, attr, v)
  227. return getter, setter
  228. def __repr__(self):
  229. return "AssociationProxy(%r, %r)" % (
  230. self.target_collection,
  231. self.value_attr,
  232. )
  233. class AssociationProxyInstance(object):
  234. """A per-class object that serves class- and object-specific results.
  235. This is used by :class:`.AssociationProxy` when it is invoked
  236. in terms of a specific class or instance of a class, i.e. when it is
  237. used as a regular Python descriptor.
  238. When referring to the :class:`.AssociationProxy` as a normal Python
  239. descriptor, the :class:`.AssociationProxyInstance` is the object that
  240. actually serves the information. Under normal circumstances, its presence
  241. is transparent::
  242. >>> User.keywords.scalar
  243. False
  244. In the special case that the :class:`.AssociationProxy` object is being
  245. accessed directly, in order to get an explicit handle to the
  246. :class:`.AssociationProxyInstance`, use the
  247. :meth:`.AssociationProxy.for_class` method::
  248. proxy_state = inspect(User).all_orm_descriptors["keywords"].for_class(User)
  249. # view if proxy object is scalar or not
  250. >>> proxy_state.scalar
  251. False
  252. .. versionadded:: 1.3
  253. """ # noqa
  254. def __init__(self, parent, owning_class, target_class, value_attr):
  255. self.parent = parent
  256. self.key = parent.key
  257. self.owning_class = owning_class
  258. self.target_collection = parent.target_collection
  259. self.collection_class = None
  260. self.target_class = target_class
  261. self.value_attr = value_attr
  262. target_class = None
  263. """The intermediary class handled by this
  264. :class:`.AssociationProxyInstance`.
  265. Intercepted append/set/assignment events will result
  266. in the generation of new instances of this class.
  267. """
  268. @classmethod
  269. def for_proxy(cls, parent, owning_class, parent_instance):
  270. target_collection = parent.target_collection
  271. value_attr = parent.value_attr
  272. prop = orm.class_mapper(owning_class).get_property(target_collection)
  273. # this was never asserted before but this should be made clear.
  274. if not isinstance(prop, orm.RelationshipProperty):
  275. util.raise_(
  276. NotImplementedError(
  277. "association proxy to a non-relationship "
  278. "intermediary is not supported"
  279. ),
  280. replace_context=None,
  281. )
  282. target_class = prop.mapper.class_
  283. try:
  284. target_assoc = cls._cls_unwrap_target_assoc_proxy(
  285. target_class, value_attr
  286. )
  287. except AttributeError:
  288. # the proxied attribute doesn't exist on the target class;
  289. # return an "ambiguous" instance that will work on a per-object
  290. # basis
  291. return AmbiguousAssociationProxyInstance(
  292. parent, owning_class, target_class, value_attr
  293. )
  294. else:
  295. return cls._construct_for_assoc(
  296. target_assoc, parent, owning_class, target_class, value_attr
  297. )
  298. @classmethod
  299. def _construct_for_assoc(
  300. cls, target_assoc, parent, owning_class, target_class, value_attr
  301. ):
  302. if target_assoc is not None:
  303. return ObjectAssociationProxyInstance(
  304. parent, owning_class, target_class, value_attr
  305. )
  306. attr = getattr(target_class, value_attr)
  307. if not hasattr(attr, "_is_internal_proxy"):
  308. return AmbiguousAssociationProxyInstance(
  309. parent, owning_class, target_class, value_attr
  310. )
  311. is_object = attr._impl_uses_objects
  312. if is_object:
  313. return ObjectAssociationProxyInstance(
  314. parent, owning_class, target_class, value_attr
  315. )
  316. else:
  317. return ColumnAssociationProxyInstance(
  318. parent, owning_class, target_class, value_attr
  319. )
  320. def _get_property(self):
  321. return orm.class_mapper(self.owning_class).get_property(
  322. self.target_collection
  323. )
  324. @property
  325. def _comparator(self):
  326. return self._get_property().comparator
  327. def __clause_element__(self):
  328. raise NotImplementedError(
  329. "The association proxy can't be used as a plain column "
  330. "expression; it only works inside of a comparison expression"
  331. )
  332. @classmethod
  333. def _cls_unwrap_target_assoc_proxy(cls, target_class, value_attr):
  334. attr = getattr(target_class, value_attr)
  335. if isinstance(attr, (AssociationProxy, AssociationProxyInstance)):
  336. return attr
  337. return None
  338. @util.memoized_property
  339. def _unwrap_target_assoc_proxy(self):
  340. return self._cls_unwrap_target_assoc_proxy(
  341. self.target_class, self.value_attr
  342. )
  343. @property
  344. def remote_attr(self):
  345. """The 'remote' class attribute referenced by this
  346. :class:`.AssociationProxyInstance`.
  347. .. seealso::
  348. :attr:`.AssociationProxyInstance.attr`
  349. :attr:`.AssociationProxyInstance.local_attr`
  350. """
  351. return getattr(self.target_class, self.value_attr)
  352. @property
  353. def local_attr(self):
  354. """The 'local' class attribute referenced by this
  355. :class:`.AssociationProxyInstance`.
  356. .. seealso::
  357. :attr:`.AssociationProxyInstance.attr`
  358. :attr:`.AssociationProxyInstance.remote_attr`
  359. """
  360. return getattr(self.owning_class, self.target_collection)
  361. @property
  362. def attr(self):
  363. """Return a tuple of ``(local_attr, remote_attr)``.
  364. This attribute was originally intended to facilitate using the
  365. :meth:`_query.Query.join` method to join across the two relationships
  366. at once, however this makes use of a deprecated calling style.
  367. To use :meth:`_sql.select.join` or :meth:`_orm.Query.join` with
  368. an association proxy, the current method is to make use of the
  369. :attr:`.AssociationProxyInstance.local_attr` and
  370. :attr:`.AssociationProxyInstance.remote_attr` attributes separately::
  371. stmt = (
  372. select(Parent).
  373. join(Parent.proxied.local_attr).
  374. join(Parent.proxied.remote_attr)
  375. )
  376. A future release may seek to provide a more succinct join pattern
  377. for association proxy attributes.
  378. .. seealso::
  379. :attr:`.AssociationProxyInstance.local_attr`
  380. :attr:`.AssociationProxyInstance.remote_attr`
  381. """
  382. return (self.local_attr, self.remote_attr)
  383. @util.memoized_property
  384. def scalar(self):
  385. """Return ``True`` if this :class:`.AssociationProxyInstance`
  386. proxies a scalar relationship on the local side."""
  387. scalar = not self._get_property().uselist
  388. if scalar:
  389. self._initialize_scalar_accessors()
  390. return scalar
  391. @util.memoized_property
  392. def _value_is_scalar(self):
  393. return (
  394. not self._get_property()
  395. .mapper.get_property(self.value_attr)
  396. .uselist
  397. )
  398. @property
  399. def _target_is_object(self):
  400. raise NotImplementedError()
  401. def _initialize_scalar_accessors(self):
  402. if self.parent.getset_factory:
  403. get, set_ = self.parent.getset_factory(None, self)
  404. else:
  405. get, set_ = self.parent._default_getset(None)
  406. self._scalar_get, self._scalar_set = get, set_
  407. def _default_getset(self, collection_class):
  408. attr = self.value_attr
  409. _getter = operator.attrgetter(attr)
  410. def getter(target):
  411. return _getter(target) if target is not None else None
  412. if collection_class is dict:
  413. def setter(o, k, v):
  414. return setattr(o, attr, v)
  415. else:
  416. def setter(o, v):
  417. return setattr(o, attr, v)
  418. return getter, setter
  419. @property
  420. def info(self):
  421. return self.parent.info
  422. def get(self, obj):
  423. if obj is None:
  424. return self
  425. if self.scalar:
  426. target = getattr(obj, self.target_collection)
  427. return self._scalar_get(target)
  428. else:
  429. try:
  430. # If the owning instance is reborn (orm session resurrect,
  431. # etc.), refresh the proxy cache.
  432. creator_id, self_id, proxy = getattr(obj, self.key)
  433. except AttributeError:
  434. pass
  435. else:
  436. if id(obj) == creator_id and id(self) == self_id:
  437. assert self.collection_class is not None
  438. return proxy
  439. self.collection_class, proxy = self._new(
  440. _lazy_collection(obj, self.target_collection)
  441. )
  442. setattr(obj, self.key, (id(obj), id(self), proxy))
  443. return proxy
  444. def set(self, obj, values):
  445. if self.scalar:
  446. creator = (
  447. self.parent.creator
  448. if self.parent.creator
  449. else self.target_class
  450. )
  451. target = getattr(obj, self.target_collection)
  452. if target is None:
  453. if values is None:
  454. return
  455. setattr(obj, self.target_collection, creator(values))
  456. else:
  457. self._scalar_set(target, values)
  458. if values is None and self.parent.cascade_scalar_deletes:
  459. setattr(obj, self.target_collection, None)
  460. else:
  461. proxy = self.get(obj)
  462. assert self.collection_class is not None
  463. if proxy is not values:
  464. proxy._bulk_replace(self, values)
  465. def delete(self, obj):
  466. if self.owning_class is None:
  467. self._calc_owner(obj, None)
  468. if self.scalar:
  469. target = getattr(obj, self.target_collection)
  470. if target is not None:
  471. delattr(target, self.value_attr)
  472. delattr(obj, self.target_collection)
  473. def _new(self, lazy_collection):
  474. creator = (
  475. self.parent.creator if self.parent.creator else self.target_class
  476. )
  477. collection_class = util.duck_type_collection(lazy_collection())
  478. if self.parent.proxy_factory:
  479. return (
  480. collection_class,
  481. self.parent.proxy_factory(
  482. lazy_collection, creator, self.value_attr, self
  483. ),
  484. )
  485. if self.parent.getset_factory:
  486. getter, setter = self.parent.getset_factory(collection_class, self)
  487. else:
  488. getter, setter = self.parent._default_getset(collection_class)
  489. if collection_class is list:
  490. return (
  491. collection_class,
  492. _AssociationList(
  493. lazy_collection, creator, getter, setter, self
  494. ),
  495. )
  496. elif collection_class is dict:
  497. return (
  498. collection_class,
  499. _AssociationDict(
  500. lazy_collection, creator, getter, setter, self
  501. ),
  502. )
  503. elif collection_class is set:
  504. return (
  505. collection_class,
  506. _AssociationSet(
  507. lazy_collection, creator, getter, setter, self
  508. ),
  509. )
  510. else:
  511. raise exc.ArgumentError(
  512. "could not guess which interface to use for "
  513. 'collection_class "%s" backing "%s"; specify a '
  514. "proxy_factory and proxy_bulk_set manually"
  515. % (self.collection_class.__name__, self.target_collection)
  516. )
  517. def _set(self, proxy, values):
  518. if self.parent.proxy_bulk_set:
  519. self.parent.proxy_bulk_set(proxy, values)
  520. elif self.collection_class is list:
  521. proxy.extend(values)
  522. elif self.collection_class is dict:
  523. proxy.update(values)
  524. elif self.collection_class is set:
  525. proxy.update(values)
  526. else:
  527. raise exc.ArgumentError(
  528. "no proxy_bulk_set supplied for custom "
  529. "collection_class implementation"
  530. )
  531. def _inflate(self, proxy):
  532. creator = (
  533. self.parent.creator and self.parent.creator or self.target_class
  534. )
  535. if self.parent.getset_factory:
  536. getter, setter = self.parent.getset_factory(
  537. self.collection_class, self
  538. )
  539. else:
  540. getter, setter = self.parent._default_getset(self.collection_class)
  541. proxy.creator = creator
  542. proxy.getter = getter
  543. proxy.setter = setter
  544. def _criterion_exists(self, criterion=None, **kwargs):
  545. is_has = kwargs.pop("is_has", None)
  546. target_assoc = self._unwrap_target_assoc_proxy
  547. if target_assoc is not None:
  548. inner = target_assoc._criterion_exists(
  549. criterion=criterion, **kwargs
  550. )
  551. return self._comparator._criterion_exists(inner)
  552. if self._target_is_object:
  553. prop = getattr(self.target_class, self.value_attr)
  554. value_expr = prop._criterion_exists(criterion, **kwargs)
  555. else:
  556. if kwargs:
  557. raise exc.ArgumentError(
  558. "Can't apply keyword arguments to column-targeted "
  559. "association proxy; use =="
  560. )
  561. elif is_has and criterion is not None:
  562. raise exc.ArgumentError(
  563. "Non-empty has() not allowed for "
  564. "column-targeted association proxy; use =="
  565. )
  566. value_expr = criterion
  567. return self._comparator._criterion_exists(value_expr)
  568. def any(self, criterion=None, **kwargs):
  569. """Produce a proxied 'any' expression using EXISTS.
  570. This expression will be a composed product
  571. using the :meth:`.RelationshipProperty.Comparator.any`
  572. and/or :meth:`.RelationshipProperty.Comparator.has`
  573. operators of the underlying proxied attributes.
  574. """
  575. if self._unwrap_target_assoc_proxy is None and (
  576. self.scalar
  577. and (not self._target_is_object or self._value_is_scalar)
  578. ):
  579. raise exc.InvalidRequestError(
  580. "'any()' not implemented for scalar " "attributes. Use has()."
  581. )
  582. return self._criterion_exists(
  583. criterion=criterion, is_has=False, **kwargs
  584. )
  585. def has(self, criterion=None, **kwargs):
  586. """Produce a proxied 'has' expression using EXISTS.
  587. This expression will be a composed product
  588. using the :meth:`.RelationshipProperty.Comparator.any`
  589. and/or :meth:`.RelationshipProperty.Comparator.has`
  590. operators of the underlying proxied attributes.
  591. """
  592. if self._unwrap_target_assoc_proxy is None and (
  593. not self.scalar
  594. or (self._target_is_object and not self._value_is_scalar)
  595. ):
  596. raise exc.InvalidRequestError(
  597. "'has()' not implemented for collections. " "Use any()."
  598. )
  599. return self._criterion_exists(
  600. criterion=criterion, is_has=True, **kwargs
  601. )
  602. def __repr__(self):
  603. return "%s(%r)" % (self.__class__.__name__, self.parent)
  604. class AmbiguousAssociationProxyInstance(AssociationProxyInstance):
  605. """an :class:`.AssociationProxyInstance` where we cannot determine
  606. the type of target object.
  607. """
  608. _is_canonical = False
  609. def _ambiguous(self):
  610. raise AttributeError(
  611. "Association proxy %s.%s refers to an attribute '%s' that is not "
  612. "directly mapped on class %s; therefore this operation cannot "
  613. "proceed since we don't know what type of object is referred "
  614. "towards"
  615. % (
  616. self.owning_class.__name__,
  617. self.target_collection,
  618. self.value_attr,
  619. self.target_class,
  620. )
  621. )
  622. def get(self, obj):
  623. if obj is None:
  624. return self
  625. else:
  626. return super(AmbiguousAssociationProxyInstance, self).get(obj)
  627. def __eq__(self, obj):
  628. self._ambiguous()
  629. def __ne__(self, obj):
  630. self._ambiguous()
  631. def any(self, criterion=None, **kwargs):
  632. self._ambiguous()
  633. def has(self, criterion=None, **kwargs):
  634. self._ambiguous()
  635. @util.memoized_property
  636. def _lookup_cache(self):
  637. # mapping of <subclass>->AssociationProxyInstance.
  638. # e.g. proxy is A-> A.b -> B -> B.b_attr, but B.b_attr doesn't exist;
  639. # only B1(B) and B2(B) have "b_attr", keys in here would be B1, B2
  640. return {}
  641. def _non_canonical_get_for_object(self, parent_instance):
  642. if parent_instance is not None:
  643. actual_obj = getattr(parent_instance, self.target_collection)
  644. if actual_obj is not None:
  645. try:
  646. insp = inspect(actual_obj)
  647. except exc.NoInspectionAvailable:
  648. pass
  649. else:
  650. mapper = insp.mapper
  651. instance_class = mapper.class_
  652. if instance_class not in self._lookup_cache:
  653. self._populate_cache(instance_class, mapper)
  654. try:
  655. return self._lookup_cache[instance_class]
  656. except KeyError:
  657. pass
  658. # no object or ambiguous object given, so return "self", which
  659. # is a proxy with generally only instance-level functionality
  660. return self
  661. def _populate_cache(self, instance_class, mapper):
  662. prop = orm.class_mapper(self.owning_class).get_property(
  663. self.target_collection
  664. )
  665. if mapper.isa(prop.mapper):
  666. target_class = instance_class
  667. try:
  668. target_assoc = self._cls_unwrap_target_assoc_proxy(
  669. target_class, self.value_attr
  670. )
  671. except AttributeError:
  672. pass
  673. else:
  674. self._lookup_cache[instance_class] = self._construct_for_assoc(
  675. target_assoc,
  676. self.parent,
  677. self.owning_class,
  678. target_class,
  679. self.value_attr,
  680. )
  681. class ObjectAssociationProxyInstance(AssociationProxyInstance):
  682. """an :class:`.AssociationProxyInstance` that has an object as a target."""
  683. _target_is_object = True
  684. _is_canonical = True
  685. def contains(self, obj):
  686. """Produce a proxied 'contains' expression using EXISTS.
  687. This expression will be a composed product
  688. using the :meth:`.RelationshipProperty.Comparator.any`,
  689. :meth:`.RelationshipProperty.Comparator.has`,
  690. and/or :meth:`.RelationshipProperty.Comparator.contains`
  691. operators of the underlying proxied attributes.
  692. """
  693. target_assoc = self._unwrap_target_assoc_proxy
  694. if target_assoc is not None:
  695. return self._comparator._criterion_exists(
  696. target_assoc.contains(obj)
  697. if not target_assoc.scalar
  698. else target_assoc == obj
  699. )
  700. elif (
  701. self._target_is_object
  702. and self.scalar
  703. and not self._value_is_scalar
  704. ):
  705. return self._comparator.has(
  706. getattr(self.target_class, self.value_attr).contains(obj)
  707. )
  708. elif self._target_is_object and self.scalar and self._value_is_scalar:
  709. raise exc.InvalidRequestError(
  710. "contains() doesn't apply to a scalar object endpoint; use =="
  711. )
  712. else:
  713. return self._comparator._criterion_exists(**{self.value_attr: obj})
  714. def __eq__(self, obj):
  715. # note the has() here will fail for collections; eq_()
  716. # is only allowed with a scalar.
  717. if obj is None:
  718. return or_(
  719. self._comparator.has(**{self.value_attr: obj}),
  720. self._comparator == None,
  721. )
  722. else:
  723. return self._comparator.has(**{self.value_attr: obj})
  724. def __ne__(self, obj):
  725. # note the has() here will fail for collections; eq_()
  726. # is only allowed with a scalar.
  727. return self._comparator.has(
  728. getattr(self.target_class, self.value_attr) != obj
  729. )
  730. class ColumnAssociationProxyInstance(
  731. ColumnOperators, AssociationProxyInstance
  732. ):
  733. """an :class:`.AssociationProxyInstance` that has a database column as a
  734. target.
  735. """
  736. _target_is_object = False
  737. _is_canonical = True
  738. def __eq__(self, other):
  739. # special case "is None" to check for no related row as well
  740. expr = self._criterion_exists(
  741. self.remote_attr.operate(operator.eq, other)
  742. )
  743. if other is None:
  744. return or_(expr, self._comparator == None)
  745. else:
  746. return expr
  747. def operate(self, op, *other, **kwargs):
  748. return self._criterion_exists(
  749. self.remote_attr.operate(op, *other, **kwargs)
  750. )
  751. class _lazy_collection(object):
  752. def __init__(self, obj, target):
  753. self.parent = obj
  754. self.target = target
  755. def __call__(self):
  756. return getattr(self.parent, self.target)
  757. def __getstate__(self):
  758. return {"obj": self.parent, "target": self.target}
  759. def __setstate__(self, state):
  760. self.parent = state["obj"]
  761. self.target = state["target"]
  762. class _AssociationCollection(object):
  763. def __init__(self, lazy_collection, creator, getter, setter, parent):
  764. """Constructs an _AssociationCollection.
  765. This will always be a subclass of either _AssociationList,
  766. _AssociationSet, or _AssociationDict.
  767. lazy_collection
  768. A callable returning a list-based collection of entities (usually an
  769. object attribute managed by a SQLAlchemy relationship())
  770. creator
  771. A function that creates new target entities. Given one parameter:
  772. value. This assertion is assumed::
  773. obj = creator(somevalue)
  774. assert getter(obj) == somevalue
  775. getter
  776. A function. Given an associated object, return the 'value'.
  777. setter
  778. A function. Given an associated object and a value, store that
  779. value on the object.
  780. """
  781. self.lazy_collection = lazy_collection
  782. self.creator = creator
  783. self.getter = getter
  784. self.setter = setter
  785. self.parent = parent
  786. col = property(lambda self: self.lazy_collection())
  787. def __len__(self):
  788. return len(self.col)
  789. def __bool__(self):
  790. return bool(self.col)
  791. __nonzero__ = __bool__
  792. def __getstate__(self):
  793. return {"parent": self.parent, "lazy_collection": self.lazy_collection}
  794. def __setstate__(self, state):
  795. self.parent = state["parent"]
  796. self.lazy_collection = state["lazy_collection"]
  797. self.parent._inflate(self)
  798. def _bulk_replace(self, assoc_proxy, values):
  799. self.clear()
  800. assoc_proxy._set(self, values)
  801. class _AssociationList(_AssociationCollection):
  802. """Generic, converting, list-to-list proxy."""
  803. def _create(self, value):
  804. return self.creator(value)
  805. def _get(self, object_):
  806. return self.getter(object_)
  807. def _set(self, object_, value):
  808. return self.setter(object_, value)
  809. def __getitem__(self, index):
  810. if not isinstance(index, slice):
  811. return self._get(self.col[index])
  812. else:
  813. return [self._get(member) for member in self.col[index]]
  814. def __setitem__(self, index, value):
  815. if not isinstance(index, slice):
  816. self._set(self.col[index], value)
  817. else:
  818. if index.stop is None:
  819. stop = len(self)
  820. elif index.stop < 0:
  821. stop = len(self) + index.stop
  822. else:
  823. stop = index.stop
  824. step = index.step or 1
  825. start = index.start or 0
  826. rng = list(range(index.start or 0, stop, step))
  827. if step == 1:
  828. for i in rng:
  829. del self[start]
  830. i = start
  831. for item in value:
  832. self.insert(i, item)
  833. i += 1
  834. else:
  835. if len(value) != len(rng):
  836. raise ValueError(
  837. "attempt to assign sequence of size %s to "
  838. "extended slice of size %s" % (len(value), len(rng))
  839. )
  840. for i, item in zip(rng, value):
  841. self._set(self.col[i], item)
  842. def __delitem__(self, index):
  843. del self.col[index]
  844. def __contains__(self, value):
  845. for member in self.col:
  846. # testlib.pragma exempt:__eq__
  847. if self._get(member) == value:
  848. return True
  849. return False
  850. def __getslice__(self, start, end):
  851. return [self._get(member) for member in self.col[start:end]]
  852. def __setslice__(self, start, end, values):
  853. members = [self._create(v) for v in values]
  854. self.col[start:end] = members
  855. def __delslice__(self, start, end):
  856. del self.col[start:end]
  857. def __iter__(self):
  858. """Iterate over proxied values.
  859. For the actual domain objects, iterate over .col instead or
  860. just use the underlying collection directly from its property
  861. on the parent.
  862. """
  863. for member in self.col:
  864. yield self._get(member)
  865. return
  866. def append(self, value):
  867. col = self.col
  868. item = self._create(value)
  869. col.append(item)
  870. def count(self, value):
  871. return sum(
  872. [
  873. 1
  874. for _ in util.itertools_filter(
  875. lambda v: v == value, iter(self)
  876. )
  877. ]
  878. )
  879. def extend(self, values):
  880. for v in values:
  881. self.append(v)
  882. def insert(self, index, value):
  883. self.col[index:index] = [self._create(value)]
  884. def pop(self, index=-1):
  885. return self.getter(self.col.pop(index))
  886. def remove(self, value):
  887. for i, val in enumerate(self):
  888. if val == value:
  889. del self.col[i]
  890. return
  891. raise ValueError("value not in list")
  892. def reverse(self):
  893. """Not supported, use reversed(mylist)"""
  894. raise NotImplementedError
  895. def sort(self):
  896. """Not supported, use sorted(mylist)"""
  897. raise NotImplementedError
  898. def clear(self):
  899. del self.col[0 : len(self.col)]
  900. def __eq__(self, other):
  901. return list(self) == other
  902. def __ne__(self, other):
  903. return list(self) != other
  904. def __lt__(self, other):
  905. return list(self) < other
  906. def __le__(self, other):
  907. return list(self) <= other
  908. def __gt__(self, other):
  909. return list(self) > other
  910. def __ge__(self, other):
  911. return list(self) >= other
  912. def __cmp__(self, other):
  913. return util.cmp(list(self), other)
  914. def __add__(self, iterable):
  915. try:
  916. other = list(iterable)
  917. except TypeError:
  918. return NotImplemented
  919. return list(self) + other
  920. def __radd__(self, iterable):
  921. try:
  922. other = list(iterable)
  923. except TypeError:
  924. return NotImplemented
  925. return other + list(self)
  926. def __mul__(self, n):
  927. if not isinstance(n, int):
  928. return NotImplemented
  929. return list(self) * n
  930. __rmul__ = __mul__
  931. def __iadd__(self, iterable):
  932. self.extend(iterable)
  933. return self
  934. def __imul__(self, n):
  935. # unlike a regular list *=, proxied __imul__ will generate unique
  936. # backing objects for each copy. *= on proxied lists is a bit of
  937. # a stretch anyhow, and this interpretation of the __imul__ contract
  938. # is more plausibly useful than copying the backing objects.
  939. if not isinstance(n, int):
  940. return NotImplemented
  941. if n == 0:
  942. self.clear()
  943. elif n > 1:
  944. self.extend(list(self) * (n - 1))
  945. return self
  946. def index(self, item, *args):
  947. return list(self).index(item, *args)
  948. def copy(self):
  949. return list(self)
  950. def __repr__(self):
  951. return repr(list(self))
  952. def __hash__(self):
  953. raise TypeError("%s objects are unhashable" % type(self).__name__)
  954. for func_name, func in list(locals().items()):
  955. if (
  956. callable(func)
  957. and func.__name__ == func_name
  958. and not func.__doc__
  959. and hasattr(list, func_name)
  960. ):
  961. func.__doc__ = getattr(list, func_name).__doc__
  962. del func_name, func
  963. _NotProvided = util.symbol("_NotProvided")
  964. class _AssociationDict(_AssociationCollection):
  965. """Generic, converting, dict-to-dict proxy."""
  966. def _create(self, key, value):
  967. return self.creator(key, value)
  968. def _get(self, object_):
  969. return self.getter(object_)
  970. def _set(self, object_, key, value):
  971. return self.setter(object_, key, value)
  972. def __getitem__(self, key):
  973. return self._get(self.col[key])
  974. def __setitem__(self, key, value):
  975. if key in self.col:
  976. self._set(self.col[key], key, value)
  977. else:
  978. self.col[key] = self._create(key, value)
  979. def __delitem__(self, key):
  980. del self.col[key]
  981. def __contains__(self, key):
  982. # testlib.pragma exempt:__hash__
  983. return key in self.col
  984. def has_key(self, key):
  985. # testlib.pragma exempt:__hash__
  986. return key in self.col
  987. def __iter__(self):
  988. return iter(self.col.keys())
  989. def clear(self):
  990. self.col.clear()
  991. def __eq__(self, other):
  992. return dict(self) == other
  993. def __ne__(self, other):
  994. return dict(self) != other
  995. def __lt__(self, other):
  996. return dict(self) < other
  997. def __le__(self, other):
  998. return dict(self) <= other
  999. def __gt__(self, other):
  1000. return dict(self) > other
  1001. def __ge__(self, other):
  1002. return dict(self) >= other
  1003. def __cmp__(self, other):
  1004. return util.cmp(dict(self), other)
  1005. def __repr__(self):
  1006. return repr(dict(self.items()))
  1007. def get(self, key, default=None):
  1008. try:
  1009. return self[key]
  1010. except KeyError:
  1011. return default
  1012. def setdefault(self, key, default=None):
  1013. if key not in self.col:
  1014. self.col[key] = self._create(key, default)
  1015. return default
  1016. else:
  1017. return self[key]
  1018. def keys(self):
  1019. return self.col.keys()
  1020. if util.py2k:
  1021. def iteritems(self):
  1022. return ((key, self._get(self.col[key])) for key in self.col)
  1023. def itervalues(self):
  1024. return (self._get(self.col[key]) for key in self.col)
  1025. def iterkeys(self):
  1026. return self.col.iterkeys()
  1027. def values(self):
  1028. return [self._get(member) for member in self.col.values()]
  1029. def items(self):
  1030. return [(k, self._get(self.col[k])) for k in self]
  1031. else:
  1032. def items(self):
  1033. return ((key, self._get(self.col[key])) for key in self.col)
  1034. def values(self):
  1035. return (self._get(self.col[key]) for key in self.col)
  1036. def pop(self, key, default=_NotProvided):
  1037. if default is _NotProvided:
  1038. member = self.col.pop(key)
  1039. else:
  1040. member = self.col.pop(key, default)
  1041. return self._get(member)
  1042. def popitem(self):
  1043. item = self.col.popitem()
  1044. return (item[0], self._get(item[1]))
  1045. def update(self, *a, **kw):
  1046. if len(a) > 1:
  1047. raise TypeError(
  1048. "update expected at most 1 arguments, got %i" % len(a)
  1049. )
  1050. elif len(a) == 1:
  1051. seq_or_map = a[0]
  1052. # discern dict from sequence - took the advice from
  1053. # https://www.voidspace.org.uk/python/articles/duck_typing.shtml
  1054. # still not perfect :(
  1055. if hasattr(seq_or_map, "keys"):
  1056. for item in seq_or_map:
  1057. self[item] = seq_or_map[item]
  1058. else:
  1059. try:
  1060. for k, v in seq_or_map:
  1061. self[k] = v
  1062. except ValueError as err:
  1063. util.raise_(
  1064. ValueError(
  1065. "dictionary update sequence "
  1066. "requires 2-element tuples"
  1067. ),
  1068. replace_context=err,
  1069. )
  1070. for key, value in kw:
  1071. self[key] = value
  1072. def _bulk_replace(self, assoc_proxy, values):
  1073. existing = set(self)
  1074. constants = existing.intersection(values or ())
  1075. additions = set(values or ()).difference(constants)
  1076. removals = existing.difference(constants)
  1077. for key, member in values.items() or ():
  1078. if key in additions:
  1079. self[key] = member
  1080. elif key in constants:
  1081. self[key] = member
  1082. for key in removals:
  1083. del self[key]
  1084. def copy(self):
  1085. return dict(self.items())
  1086. def __hash__(self):
  1087. raise TypeError("%s objects are unhashable" % type(self).__name__)
  1088. for func_name, func in list(locals().items()):
  1089. if (
  1090. callable(func)
  1091. and func.__name__ == func_name
  1092. and not func.__doc__
  1093. and hasattr(dict, func_name)
  1094. ):
  1095. func.__doc__ = getattr(dict, func_name).__doc__
  1096. del func_name, func
  1097. class _AssociationSet(_AssociationCollection):
  1098. """Generic, converting, set-to-set proxy."""
  1099. def _create(self, value):
  1100. return self.creator(value)
  1101. def _get(self, object_):
  1102. return self.getter(object_)
  1103. def __len__(self):
  1104. return len(self.col)
  1105. def __bool__(self):
  1106. if self.col:
  1107. return True
  1108. else:
  1109. return False
  1110. __nonzero__ = __bool__
  1111. def __contains__(self, value):
  1112. for member in self.col:
  1113. # testlib.pragma exempt:__eq__
  1114. if self._get(member) == value:
  1115. return True
  1116. return False
  1117. def __iter__(self):
  1118. """Iterate over proxied values.
  1119. For the actual domain objects, iterate over .col instead or just use
  1120. the underlying collection directly from its property on the parent.
  1121. """
  1122. for member in self.col:
  1123. yield self._get(member)
  1124. return
  1125. def add(self, value):
  1126. if value not in self:
  1127. self.col.add(self._create(value))
  1128. # for discard and remove, choosing a more expensive check strategy rather
  1129. # than call self.creator()
  1130. def discard(self, value):
  1131. for member in self.col:
  1132. if self._get(member) == value:
  1133. self.col.discard(member)
  1134. break
  1135. def remove(self, value):
  1136. for member in self.col:
  1137. if self._get(member) == value:
  1138. self.col.discard(member)
  1139. return
  1140. raise KeyError(value)
  1141. def pop(self):
  1142. if not self.col:
  1143. raise KeyError("pop from an empty set")
  1144. member = self.col.pop()
  1145. return self._get(member)
  1146. def update(self, other):
  1147. for value in other:
  1148. self.add(value)
  1149. def _bulk_replace(self, assoc_proxy, values):
  1150. existing = set(self)
  1151. constants = existing.intersection(values or ())
  1152. additions = set(values or ()).difference(constants)
  1153. removals = existing.difference(constants)
  1154. appender = self.add
  1155. remover = self.remove
  1156. for member in values or ():
  1157. if member in additions:
  1158. appender(member)
  1159. elif member in constants:
  1160. appender(member)
  1161. for member in removals:
  1162. remover(member)
  1163. def __ior__(self, other):
  1164. if not collections._set_binops_check_strict(self, other):
  1165. return NotImplemented
  1166. for value in other:
  1167. self.add(value)
  1168. return self
  1169. def _set(self):
  1170. return set(iter(self))
  1171. def union(self, other):
  1172. return set(self).union(other)
  1173. __or__ = union
  1174. def difference(self, other):
  1175. return set(self).difference(other)
  1176. __sub__ = difference
  1177. def difference_update(self, other):
  1178. for value in other:
  1179. self.discard(value)
  1180. def __isub__(self, other):
  1181. if not collections._set_binops_check_strict(self, other):
  1182. return NotImplemented
  1183. for value in other:
  1184. self.discard(value)
  1185. return self
  1186. def intersection(self, other):
  1187. return set(self).intersection(other)
  1188. __and__ = intersection
  1189. def intersection_update(self, other):
  1190. want, have = self.intersection(other), set(self)
  1191. remove, add = have - want, want - have
  1192. for value in remove:
  1193. self.remove(value)
  1194. for value in add:
  1195. self.add(value)
  1196. def __iand__(self, other):
  1197. if not collections._set_binops_check_strict(self, other):
  1198. return NotImplemented
  1199. want, have = self.intersection(other), set(self)
  1200. remove, add = have - want, want - have
  1201. for value in remove:
  1202. self.remove(value)
  1203. for value in add:
  1204. self.add(value)
  1205. return self
  1206. def symmetric_difference(self, other):
  1207. return set(self).symmetric_difference(other)
  1208. __xor__ = symmetric_difference
  1209. def symmetric_difference_update(self, other):
  1210. want, have = self.symmetric_difference(other), set(self)
  1211. remove, add = have - want, want - have
  1212. for value in remove:
  1213. self.remove(value)
  1214. for value in add:
  1215. self.add(value)
  1216. def __ixor__(self, other):
  1217. if not collections._set_binops_check_strict(self, other):
  1218. return NotImplemented
  1219. want, have = self.symmetric_difference(other), set(self)
  1220. remove, add = have - want, want - have
  1221. for value in remove:
  1222. self.remove(value)
  1223. for value in add:
  1224. self.add(value)
  1225. return self
  1226. def issubset(self, other):
  1227. return set(self).issubset(other)
  1228. def issuperset(self, other):
  1229. return set(self).issuperset(other)
  1230. def clear(self):
  1231. self.col.clear()
  1232. def copy(self):
  1233. return set(self)
  1234. def __eq__(self, other):
  1235. return set(self) == other
  1236. def __ne__(self, other):
  1237. return set(self) != other
  1238. def __lt__(self, other):
  1239. return set(self) < other
  1240. def __le__(self, other):
  1241. return set(self) <= other
  1242. def __gt__(self, other):
  1243. return set(self) > other
  1244. def __ge__(self, other):
  1245. return set(self) >= other
  1246. def __repr__(self):
  1247. return repr(set(self))
  1248. def __hash__(self):
  1249. raise TypeError("%s objects are unhashable" % type(self).__name__)
  1250. for func_name, func in list(locals().items()):
  1251. if (
  1252. callable(func)
  1253. and func.__name__ == func_name
  1254. and not func.__doc__
  1255. and hasattr(set, func_name)
  1256. ):
  1257. func.__doc__ = getattr(set, func_name).__doc__
  1258. del func_name, func