MCPcopy
hub / github.com/django/django / SimpleLazyObject

Class SimpleLazyObject

django/utils/functional.py:383–441  ·  view source on GitHub ↗

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.

Source from the content-addressed store, hash-verified

381
382
383class 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):

Callers 15

process_requestMethod · 0.90
prefix_validation_errorFunction · 0.90
update_level_tagsFunction · 0.90
base.pyFile · 0.90
libgeos.pyFile · 0.90
io.pyFile · 0.90
_lazy_re_compileFunction · 0.90
requestMethod · 0.90
requestMethod · 0.90
csrfFunction · 0.90
lazy_wrapMethod · 0.90

Calls 1

new_method_proxyFunction · 0.85

Tested by 13

lazy_wrapMethod · 0.72
test_noneMethod · 0.72
test_dictMethod · 0.72
test_list_setMethod · 0.72
test_pickle_modelMethod · 0.72
test_force_str_lazyMethod · 0.72
test_pickleMethod · 0.72
test_callable_urlconfMethod · 0.72