Reputation: 467
Looking in django.utils.functional
I noticed a LazyObject
class, django uses it in django.conf
:
class LazySettings(LazyObject):
it is the defination of LazyObject
:
class LazyObject(object):
"""
A wrapper for another class that can be used to delay instantiation of the
wrapped class.
By subclassing, you have the opportunity to intercept and alter the
instantiation. If you don't need to do that, use SimpleLazyObject.
"""
def __init__(self):
self._wrapped = None
def __getattr__(self, name):
if self._wrapped is None:
self._setup()
return getattr(self._wrapped, name)
def __setattr__(self, name, value):
if name == "_wrapped":
# Assign to __dict__ to avoid infinite __setattr__ loops.
self.__dict__["_wrapped"] = value
else:
if self._wrapped is None:
self._setup()
setattr(self._wrapped, name, value)
def __delattr__(self, name):
if name == "_wrapped":
raise TypeError("can't delete _wrapped.")
if self._wrapped is None:
self._setup()
delattr(self._wrapped, name)
def _setup(self):
"""
Must be implemented by subclasses to initialise the wrapped object.
"""
raise NotImplementedError
# introspection support:
__members__ = property(lambda self: self.__dir__())
def __dir__(self):
if self._wrapped is None:
self._setup()
return dir(self._wrapped)
i want to know what is the best situation to use the LazyObject
?
Upvotes: 3
Views: 1432
Reputation: 1948
It based on exp. As I know:
1. Get a data and you do not use it now and still operate it, like QuerySet in django
2. A data u can tell where to load/read it now, like configuration.
3. proxy
4. Large set of data and just use part on it now.
And more...
Upvotes: 1