Skip to content

Support for the descriptor protocol for lazy_import'ed objects #11224

@nthiery

Description

@nthiery

This patch enable to lazy import objects using the descriptor protocol (readonly at this point: just the __get__ method).

A sample application taken from the doc::

Here we show how to take a function in a module, and lazy
import it as a method of a class. For the sake of this
example, we add manually a function in sage.all::

    sage: def my_method(self): return self
    sage: sage.all.my_method = my_method

Now we lazy import it as a method of a new class ``Foo``::

    sage: from sage.misc.lazy_import import LazyImport
    sage: class Foo:
    ...       my_method = LazyImport('sage.all', 'my_method')

Now we can use it as a usual method::

    sage: Foo().my_method()
    <__main__.Foo instance at ...>
    sage: Foo.my_method
    <unbound method Foo.my_method>
    sage: Foo().my_method
    <bound method Foo.my_method of <__main__.Foo instance at ...>>

Currently, ``my_method`` remains a lazy imported object in the
class dictionary, even when it has already been used, which is
not as efficient as it could be (but see #11003)::

    sage: type(Foo.__dict__["my_method"])
    <type 'sage.misc.lazy_import.LazyImport'>

In practice, I needed this feature for further work on categories and functorial constructions, around #11111 and #10963.

CC: @rishikesha @jasongrout @rlmill

Component: misc

Keywords: sd31

Author: Nicolas M. Thiéry

Reviewer: Mike Hansen

Merged: sage-4.7.2.alpha1

Issue created by migration from https://trac.sagemath.org/ticket/11224

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions