示例#1
0
    class LazyObject(LazyObject):
        # Dictionary methods support
        __getitem__ = new_method_proxy(operator.getitem)
        __setitem__ = new_method_proxy(operator.setitem)
        __delitem__ = new_method_proxy(operator.delitem)

        __len__ = new_method_proxy(len)
        __contains__ = new_method_proxy(operator.contains)
示例#2
0
class LazyEDBVersion(SimpleLazyObject):
    def __init__(self, obj, getter):
        super(LazyEDBVersion, self).__init__(
            lambda: EduroamDatabaseVersion(getter(obj)))
    # def __repr__(self):
    #     return repr(self._wrapped)
    __lt__ = new_method_proxy(operator.lt)
    __le__ = new_method_proxy(operator.le)
    __gt__ = new_method_proxy(operator.gt)
    __ge__ = new_method_proxy(operator.ge)
    __hash__ = new_method_proxy(operator.methodcaller('__hash__'))
示例#3
0
class LazyDocumentMetaWrapper(LazyObject):
    _document = None
    _meta = None

    def __init__(self, document):
        self._document = document
        self._meta = document._meta
        super(LazyDocumentMetaWrapper, self).__init__()

    def _setup(self):
        self._wrapped = DocumentMetaWrapper(self._document, self._meta)

    def __setattr__(self, name, value):
        if name in [
                "_document",
                "_meta",
        ]:
            object.__setattr__(self, name, value)
        else:
            super(LazyDocumentMetaWrapper, self).__setattr__(name, value)

    __len__ = new_method_proxy(len)

    @new_method_proxy
    def __contains__(self, key):
        return key in self
示例#4
0
class LazySettings(DjangoLazySettings):
    settings_class = None

    def get_settings_class(self):
        return self.settings_class or Settings

    def _setup(self, name=None):
        settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
        if not settings_module:
            desc = ('setting %s' % name) if name else 'settings'
            raise ImproperlyConfigured(
                'Requested %s, but settings are not configured. '
                'You must either define the environment variable %s '
                'or call settings.configure() before accessing settings.'
                % (desc, ENVIRONMENT_VARIABLE))

        self._wrapped = self.get_settings_class()(settings_module)

    if django.VERSION[:2] < (2, 0):
        # avoid maximum recursion depth exception

        def __setattr__(self, name, value):
            if name == '_wrapped':
                self.__dict__.clear()
            else:
                self.__dict__.pop(name, None)
            super(DjangoLazySettings, self).__setattr__(name, value)

        def __delattr__(self, name):
            if name == '_wrapped':
                raise TypeError("can't delete _wrapped.")
            super(DjangoLazySettings, self).__delattr__(name)
            self.__dict__.pop(name, None)

    if django.VERSION[:2] < (2, 2):
        __lt__ = new_method_proxy(operator.lt)
        __gt__ = new_method_proxy(operator.gt)
示例#5
0
class LazyList(SimpleLazyObject):
  """
  List which populates itself from populate() callable when accessed first time.
  """
  
  def __init__(self, populate, *args, **kvargs):
    super(LazyList, self).__init__()
    self._populate = populate
    self._args = args
    self._kvargs = kvargs
  
  def _setup(self):
    self._wrapped = self._populate(*self._args, **self._kvargs)
  
  def __setattr__(self, name, value):
    if name in ('_populate', '_wrapped', '_args', '_kvargs'):
      self.__dict__[name] = value
    else:
      if self._wrapped is empty:
        self._setup()
      setattr(self._wrapped, name, value)

  __iter__ = new_method_proxy(iter)
示例#6
0
class FixedSimpleLazyObject(SimpleLazyObject):
    if not hasattr(SimpleLazyObject, '__iter__'):
        __iter__ = new_method_proxy(iter)
示例#7
0
    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.
        """

        # Avoid infinite recursion when tracing __init__ (#19456).
        _wrapped = None

        def __init__(self):
            # Note: if a subclass overrides __init__(), it will likely need to
            # override __copy__() and __deepcopy__() as well.
            self._wrapped = empty

        __getattr__ = new_method_proxy(getattr)

        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 empty:
                    self._setup()
                setattr(self._wrapped, name, value)

        def __delattr__(self, name):
            if name == "_wrapped":
                raise TypeError("can't delete _wrapped.")
            if self._wrapped is empty:
                self._setup()
            delattr(self._wrapped, name)

        def _setup(self):
            """
            Must be implemented by subclasses to initialize the wrapped object.
            """
            raise NotImplementedError(
                'subclasses of LazyObject must provide a _setup() method')

        # Because we have messed with __class__ below, we confuse pickle as to what
        # class we are pickling. We're going to have to initialize the wrapped
        # object to successfully pickle it, so we might as well just pickle the
        # wrapped object since they're supposed to act the same way.
        #
        # Unfortunately, if we try to simply act like the wrapped object, the ruse
        # will break down when pickle gets our id(). Thus we end up with pickle
        # thinking, in effect, that we are a distinct object from the wrapped
        # object, but with the same __dict__. This can cause problems (see #25389).
        #
        # So instead, we define our own __reduce__ method and custom unpickler. We
        # pickle the wrapped object as the unpickler's argument, so that pickle
        # will pickle it normally, and then the unpickler simply returns its
        # argument.
        def __reduce__(self):
            if self._wrapped is empty:
                self._setup()
            return (unpickle_lazyobject, (self._wrapped, ))

        # Overriding __class__ stops __reduce__ from being called on Python 2.
        # So, define __getstate__ in a way that cooperates with the way that
        # pickle interprets this class. This fails when the wrapped class is a
        # builtin, but it's better than nothing.
        def __getstate__(self):
            if self._wrapped is empty:
                self._setup()
            return self._wrapped.__dict__

        def __copy__(self):
            if self._wrapped is empty:
                # If uninitialized, copy the wrapper. Use type(self), not
                # self.__class__, because the latter is proxied.
                return type(self)()
            else:
                # If initialized, return a copy of the wrapped object.
                return copy.copy(self._wrapped)

        def __deepcopy__(self, memo):
            if self._wrapped is empty:
                # We have to use type(self), not self.__class__, because the
                # latter is proxied.
                result = type(self)()
                memo[id(self)] = result
                return result
            return copy.deepcopy(self._wrapped, memo)

        if six.PY3:
            __bytes__ = new_method_proxy(bytes)
            __str__ = new_method_proxy(str)
            __bool__ = new_method_proxy(bool)
        else:
            __str__ = new_method_proxy(str)
            __unicode__ = new_method_proxy(
                unicode)  # NOQA: unicode undefined on PY3
            __nonzero__ = new_method_proxy(bool)

        # Introspection support
        __dir__ = new_method_proxy(dir)

        # Need to pretend to be the wrapped class, for the sake of objects that
        # care about this (especially in equality tests)
        __class__ = property(new_method_proxy(
            operator.attrgetter("__class__")))
        __eq__ = new_method_proxy(operator.eq)
        __ne__ = new_method_proxy(operator.ne)
        __hash__ = new_method_proxy(hash)

        # List/Tuple/Dictionary methods support
        __getitem__ = new_method_proxy(operator.getitem)
        __setitem__ = new_method_proxy(operator.setitem)
        __delitem__ = new_method_proxy(operator.delitem)
        __iter__ = new_method_proxy(iter)
        __len__ = new_method_proxy(len)
        __contains__ = new_method_proxy(operator.contains)
 class SimpleLazyObject(LazyObj):
     __iter__ = new_method_proxy(iter)