A lazy object initialized from any function. Designed for compound objects of unknown type. For builtins or objects of known type, use django.utils.functional.lazy.
| 381 | |
| 382 | |
| 383 | class SimpleLazyObject(LazyObject): |
| 384 | """ |
| 385 | A lazy object initialized from any function. |
| 386 | |
| 387 | Designed for compound objects of unknown type. For builtins or objects of |
| 388 | known type, use django.utils.functional.lazy. |
| 389 | """ |
| 390 | |
| 391 | def __init__(self, func): |
| 392 | """ |
| 393 | Pass in a callable that returns the object to be wrapped. |
| 394 | |
| 395 | If copies are made of the resulting SimpleLazyObject, which can happen |
| 396 | in various circumstances within Django, then you must ensure that the |
| 397 | callable can be safely run more than once and will return the same |
| 398 | value. |
| 399 | """ |
| 400 | self.__dict__["_setupfunc"] = func |
| 401 | super().__init__() |
| 402 | |
| 403 | def _setup(self): |
| 404 | self._wrapped = self._setupfunc() |
| 405 | |
| 406 | # Return a meaningful representation of the lazy object for debugging |
| 407 | # without evaluating the wrapped object. |
| 408 | def __repr__(self): |
| 409 | if self._wrapped is empty: |
| 410 | # Avoid recursion if setupfunc is a bound method of this instance. |
| 411 | if getattr(self._setupfunc, "__self__", None) is self: |
| 412 | repr_attr = f"<bound method {self._setupfunc.__name__}>" |
| 413 | else: |
| 414 | repr_attr = self._setupfunc |
| 415 | else: |
| 416 | repr_attr = self._wrapped |
| 417 | return "<%s: %r>" % (type(self).__name__, repr_attr) |
| 418 | |
| 419 | def __copy__(self): |
| 420 | if self._wrapped is empty: |
| 421 | # If uninitialized, copy the wrapper. Use SimpleLazyObject, not |
| 422 | # self.__class__, because the latter is proxied. |
| 423 | return SimpleLazyObject(self._setupfunc) |
| 424 | else: |
| 425 | # If initialized, return a copy of the wrapped object. |
| 426 | return copy.copy(self._wrapped) |
| 427 | |
| 428 | def __deepcopy__(self, memo): |
| 429 | if self._wrapped is empty: |
| 430 | # We have to use SimpleLazyObject, not self.__class__, because the |
| 431 | # latter is proxied. |
| 432 | result = SimpleLazyObject(self._setupfunc) |
| 433 | memo[id(self)] = result |
| 434 | return result |
| 435 | return copy.deepcopy(self._wrapped, memo) |
| 436 | |
| 437 | __add__ = new_method_proxy(operator.add) |
| 438 | |
| 439 | @new_method_proxy |
| 440 | def __radd__(self, other): |