示例#1
0
    def _instancedoc_(self):
        """
        Provide documentation for the wrapped function.

        TESTS::

            sage: from sage.misc.sageinspect import sage_getdoc
            sage: from sage.sets.set_from_iterator import Decorator
            sage: d = Decorator()
            sage: d.f = Integer.is_prime
            sage: print(sage_getdoc(d))   # indirect doctest
               Test whether "self" is prime.
            ...
               Calls the PARI "isprime" function.
        """
        from sage.misc.sageinspect import sage_getsourcelines, sage_getfile, _extract_embedded_position
        f = self.f
        doc = f.__doc__ or ''
        if _extract_embedded_position(doc) is None:
            try:
                sourcelines = sage_getsourcelines(f)
                from sage.env import SAGE_LIB, SAGE_SRC
                filename = sage_getfile(f)
                # The following is a heuristics to get
                # the file name of the cached function
                # or method
                if filename.startswith(SAGE_SRC):
                    filename = filename[len(SAGE_SRC):]
                elif filename.startswith(SAGE_LIB):
                    filename = filename[len(SAGE_LIB):]
                file_info = "File: %s (starting at line %d)\n"%(filename,sourcelines[1])
                doc = file_info+doc
            except IOError:
                pass
        return doc
示例#2
0
    def _sage_doc_(self):
        """
        Provide documentation for the wrapped function.

        TESTS::

            sage: from sage.misc.sageinspect import sage_getdoc
            sage: from sage.sets.set_from_iterator import Decorator
            sage: d = Decorator()
            sage: d.f = Integer.is_prime
            sage: print sage_getdoc(d)   # indirect doctest
               Test whether "self" is prime.
            ...
               Calls the PARI "isprime" function.
        """
        from sage.misc.sageinspect import sage_getsourcelines, sage_getfile, _extract_embedded_position
        f = self.f
        doc = f.__doc__ or ''
        if _extract_embedded_position(doc) is None:
            try:
                sourcelines = sage_getsourcelines(f)
                from sage.env import SAGE_LIB, SAGE_SRC
                filename = sage_getfile(f)
                # The following is a heuristics to get
                # the file name of the cached function
                # or method
                if filename.startswith(SAGE_SRC):
                    filename = filename[len(SAGE_SRC):]
                elif filename.startswith(SAGE_LIB):
                    filename = filename[len(SAGE_LIB):]
                file_info = "File: %s (starting at line %d)\n"%(filename,sourcelines[1])
                doc = file_info+doc
            except IOError:
                pass
        return doc
示例#3
0
def gen_rest_table_index(list_of_entries,
                         names=None,
                         sort=True,
                         only_local_functions=True):
    r"""
    Return a ReST table describing a list of functions.

    The list of functions can either be given explicitly, or implicitly as the
    functions/methods of a module or class.

    In the case of a class, only non-inherited methods are listed.

    INPUT:

    - ``list_of_entries`` -- a list of functions, a module or a class. If given
      a list of functions, the generated table will consist of these. If given a
      module or a class, all functions/methods it defines will be listed, except
      deprecated or those starting with an underscore. In the case of a class,
      note that inherited methods are not displayed.

    - ``names`` -- a dictionary associating a name to a function. Takes
      precedence over the automatically computed name for the functions. Only
      used when ``list_of_entries`` is a list.

    - ``sort`` (boolean; ``True``) -- whether to sort the list of methods
      lexicographically.

    - ``only_local_functions`` (boolean; ``True``) -- if ``list_of_entries`` is
      a module, ``only_local_functions = True`` means that imported functions
      will be filtered out. This can be useful to disable for making indexes of
      e.g. catalog modules such as :mod:`sage.coding.codes_catalog`.

    .. WARNING::

        The ReST tables returned by this function use '@' as a delimiter for
        cells. This can cause trouble if the first sentence in the documentation
        of a function contains the '@' character.

    EXAMPLES::

        sage: from sage.misc.rest_index_of_methods import gen_rest_table_index
        sage: print(gen_rest_table_index([graphs.PetersenGraph]))
        .. csv-table::
           :class: contentstable
           :widths: 30, 70
           :delim: @
        <BLANKLINE>
           :func:`~sage.graphs.generators.smallgraphs.PetersenGraph` @ Returns the Petersen Graph.

    The table of a module::

        sage: print(gen_rest_table_index(sage.misc.rest_index_of_methods))
        .. csv-table::
           :class: contentstable
           :widths: 30, 70
           :delim: @
        <BLANKLINE>
           :func:`~sage.misc.rest_index_of_methods.doc_index` @ Attribute an index name to a function.
           :func:`~sage.misc.rest_index_of_methods.gen_rest_table_index` @ Return a ReST table describing a list of functions.
           :func:`~sage.misc.rest_index_of_methods.gen_thematic_rest_table_index` @ Return a ReST string of thematically sorted function (or methods) of a module (or class).
           :func:`~sage.misc.rest_index_of_methods.list_of_subfunctions` @ Returns the functions (resp. methods) of a given module (resp. class) with their names.
        <BLANKLINE>
        <BLANKLINE>

    The table of a class::

        sage: print(gen_rest_table_index(Graph))
        .. csv-table::
           :class: contentstable
           :widths: 30, 70
           :delim: @
        ...
           :meth:`~sage.graphs.graph.Graph.sparse6_string` @ Return the sparse6 representation of the graph as an ASCII string.
        ...

    TESTS:

    When the first sentence of the docstring spans over several lines::

        sage: def a():
        ....:     r'''
        ....:     Here is a very very very long sentence
        ....:     that spans on several lines.
        ....:
        ....:     EXAMP...
        ....:     '''
        ....:     print("hey")
        sage: 'Here is a very very very long sentence that spans on several lines' in gen_rest_table_index([a])
        True

    The inherited methods do not show up::

        sage: gen_rest_table_index(sage.combinat.posets.lattices.FiniteLatticePoset).count('\n') < 65
        True
        sage: from sage.graphs.generic_graph import GenericGraph
        sage: A = gen_rest_table_index(Graph).count('\n')
        sage: B = gen_rest_table_index(GenericGraph).count('\n')
        sage: A < B
        True

    When ``only_local_functions`` is ``False``, we do not include
    ``gen_rest_table_index`` itself::

        sage: print(gen_rest_table_index(sage.misc.rest_index_of_methods, only_local_functions=True))
        .. csv-table::
           :class: contentstable
           :widths: 30, 70
           :delim: @
        <BLANKLINE>
           :func:`~sage.misc.rest_index_of_methods.doc_index` @ Attribute an index name to a function.
           :func:`~sage.misc.rest_index_of_methods.gen_rest_table_index` @ Return a ReST table describing a list of functions.
           :func:`~sage.misc.rest_index_of_methods.gen_thematic_rest_table_index` @ Return a ReST string of thematically sorted function (or methods) of a module (or class).
           :func:`~sage.misc.rest_index_of_methods.list_of_subfunctions` @ Returns the functions (resp. methods) of a given module (resp. class) with their names.
        <BLANKLINE>
        <BLANKLINE>
        sage: print(gen_rest_table_index(sage.misc.rest_index_of_methods, only_local_functions=False))
        .. csv-table::
           :class: contentstable
           :widths: 30, 70
           :delim: @
        <BLANKLINE>
           :func:`~sage.misc.rest_index_of_methods.doc_index` @ Attribute an index name to a function.
           :func:`~sage.misc.rest_index_of_methods.gen_thematic_rest_table_index` @ Return a ReST string of thematically sorted function (or methods) of a module (or class).
           :func:`~sage.misc.rest_index_of_methods.list_of_subfunctions` @ Returns the functions (resp. methods) of a given module (resp. class) with their names.
        <BLANKLINE>
        <BLANKLINE>

    A function that is imported into a class under a different name is listed
    under its 'new' name::

        sage: 'cliques_maximum' in gen_rest_table_index(Graph)
        True
        sage: 'all_max_cliques`' in gen_rest_table_index(Graph)
        False
    """
    import inspect
    if names is None:
        names = {}

    # If input is a class/module, we list all its non-private and methods/functions
    if (inspect.isclass(list_of_entries) or inspect.ismodule(list_of_entries)):
        root = list_of_entries
        list_of_entries, names = list_of_subfunctions(
            root, only_local_functions=only_local_functions)

    fname = lambda x: names.get(x, getattr(x, "__name__", ""))

    assert isinstance(list_of_entries, list)

    s = (".. csv-table::\n"
         "   :class: contentstable\n"
         "   :widths: 30, 70\n"
         "   :delim: @\n\n")

    if sort:
        list_of_entries.sort(key=fname)

    for e in list_of_entries:

        if inspect.ismethod(e):
            link = ":meth:`~" + str(e.im_class.__module__) + "." + str(
                e.im_class.__name__) + "." + fname(e) + "`"
        elif inspect.isfunction(e):
            link = ":func:`~" + str(e.__module__) + "." + fname(e) + "`"
        else:
            continue

        # Extract lines injected by cython
        doc = e.__doc__
        doc_tmp = _extract_embedded_position(doc)
        if doc_tmp:
            doc = doc_tmp[0]

        # Descriptions of the method/function
        if doc:
            desc = doc.split('\n\n')[0]  # first paragraph
            desc = " ".join([x.strip()
                             for x in desc.splitlines()])  # concatenate lines
            desc = desc.strip()  # remove leading spaces
        else:
            desc = "NO DOCSTRING"

        s += "   {} @ {}\n".format(link, desc.lstrip())

    return s + '\n'
def gen_rest_table_index(list_of_entries, names=None, sort=True, only_local_functions=True):
    r"""
    Return a ReST table describing a list of functions.

    The list of functions can either be given explicitly, or implicitly as the
    functions/methods of a module or class.

    In the case of a class, only non-inherited methods are listed.

    INPUT:

    - ``list_of_entries`` -- a list of functions, a module or a class. If given
      a list of functions, the generated table will consist of these. If given a
      module or a class, all functions/methods it defines will be listed, except
      deprecated or those starting with an underscore. In the case of a class,
      note that inherited methods are not displayed.

    - ``names`` -- a dictionary associating a name to a function. Takes
      precedence over the automatically computed name for the functions. Only
      used when ``list_of_entries`` is a list.

    - ``sort`` (boolean; ``True``) -- whether to sort the list of methods
      lexicographically.

    - ``only_local_functions`` (boolean; ``True``) -- if ``list_of_entries`` is
      a module, ``only_local_functions = True`` means that imported functions
      will be filtered out. This can be useful to disable for making indexes of
      e.g. catalog modules such as :mod:`sage.coding.codes_catalog`.

    .. WARNING::

        The ReST tables returned by this function use '@' as a delimiter for
        cells. This can cause trouble if the first sentence in the documentation
        of a function contains the '@' character.

    EXAMPLES::

        sage: from sage.misc.rest_index_of_methods import gen_rest_table_index
        sage: print(gen_rest_table_index([graphs.PetersenGraph]))
        .. csv-table::
           :class: contentstable
           :widths: 30, 70
           :delim: @
        <BLANKLINE>
           :func:`~sage.graphs.generators.smallgraphs.PetersenGraph` @ Returns the Petersen Graph.

    The table of a module::

        sage: print(gen_rest_table_index(sage.misc.rest_index_of_methods))
        .. csv-table::
           :class: contentstable
           :widths: 30, 70
           :delim: @
        <BLANKLINE>
           :func:`~sage.misc.rest_index_of_methods.doc_index` @ Attribute an index name to a function.
           :func:`~sage.misc.rest_index_of_methods.gen_rest_table_index` @ Return a ReST table describing a list of functions.
           :func:`~sage.misc.rest_index_of_methods.gen_thematic_rest_table_index` @ Return a ReST string of thematically sorted function (or methods) of a module (or class).
           :func:`~sage.misc.rest_index_of_methods.list_of_subfunctions` @ Returns the functions (resp. methods) of a given module (resp. class) with their names.
        <BLANKLINE>
        <BLANKLINE>

    The table of a class::

        sage: print(gen_rest_table_index(Graph))
        .. csv-table::
           :class: contentstable
           :widths: 30, 70
           :delim: @
        ...
           :meth:`~sage.graphs.graph.Graph.sparse6_string` @ Return the sparse6 representation of the graph as an ASCII string.
        ...

    TESTS:

    When the first sentence of the docstring spans over several lines::

        sage: def a():
        ....:     r'''
        ....:     Here is a very very very long sentence
        ....:     that spans on several lines.
        ....:
        ....:     EXAMP...
        ....:     '''
        ....:     print("hey")
        sage: 'Here is a very very very long sentence that spans on several lines' in gen_rest_table_index([a])
        True

    The inherited methods do not show up::

        sage: gen_rest_table_index(sage.combinat.posets.lattices.FiniteLatticePoset).count('\n') < 75
        True
        sage: from sage.graphs.generic_graph import GenericGraph
        sage: A = gen_rest_table_index(Graph).count('\n')
        sage: B = gen_rest_table_index(GenericGraph).count('\n')
        sage: A < B
        True

    When ``only_local_functions`` is ``False``, we do not include
    ``gen_rest_table_index`` itself::

        sage: print(gen_rest_table_index(sage.misc.rest_index_of_methods, only_local_functions=True))
        .. csv-table::
           :class: contentstable
           :widths: 30, 70
           :delim: @
        <BLANKLINE>
           :func:`~sage.misc.rest_index_of_methods.doc_index` @ Attribute an index name to a function.
           :func:`~sage.misc.rest_index_of_methods.gen_rest_table_index` @ Return a ReST table describing a list of functions.
           :func:`~sage.misc.rest_index_of_methods.gen_thematic_rest_table_index` @ Return a ReST string of thematically sorted function (or methods) of a module (or class).
           :func:`~sage.misc.rest_index_of_methods.list_of_subfunctions` @ Returns the functions (resp. methods) of a given module (resp. class) with their names.
        <BLANKLINE>
        <BLANKLINE>
        sage: print(gen_rest_table_index(sage.misc.rest_index_of_methods, only_local_functions=False))
        .. csv-table::
           :class: contentstable
           :widths: 30, 70
           :delim: @
        <BLANKLINE>
           :func:`~sage.misc.rest_index_of_methods.doc_index` @ Attribute an index name to a function.
           :func:`~sage.misc.rest_index_of_methods.gen_thematic_rest_table_index` @ Return a ReST string of thematically sorted function (or methods) of a module (or class).
           :func:`~sage.misc.rest_index_of_methods.list_of_subfunctions` @ Returns the functions (resp. methods) of a given module (resp. class) with their names.
        <BLANKLINE>
        <BLANKLINE>

    A function that is imported into a class under a different name is listed
    under its 'new' name::

        sage: 'cliques_maximum' in gen_rest_table_index(Graph)
        True
        sage: 'all_max_cliques`' in gen_rest_table_index(Graph)
        False
    """
    import inspect
    if names is None:
        names = {}

    # If input is a class/module, we list all its non-private and methods/functions
    if (inspect.isclass(list_of_entries) or
        inspect.ismodule(list_of_entries)):
        root = list_of_entries
        list_of_entries,names = list_of_subfunctions(root, only_local_functions=only_local_functions)

    fname = lambda x:names.get(x,getattr(x,"__name__",""))

    assert isinstance(list_of_entries,list)

    s = (".. csv-table::\n"
         "   :class: contentstable\n"
         "   :widths: 30, 70\n"
         "   :delim: @\n\n")

    if sort:
        list_of_entries.sort(key=fname)

    for e in list_of_entries:

        if inspect.ismethod(e):
            link = ":meth:`~"+str(e.im_class.__module__)+"."+str(e.im_class.__name__)+"."+fname(e)+"`"
        elif inspect.isfunction(e):
            link = ":func:`~"+str(e.__module__)+"."+fname(e)+"`"
        else:
            continue

        # Extract lines injected by cython
        doc = e.__doc__
        doc_tmp = _extract_embedded_position(doc)
        if doc_tmp:
            doc = doc_tmp[0]

        # Descriptions of the method/function
        if doc:
            desc = doc.split('\n\n')[0]                             # first paragraph
            desc = " ".join([x.strip() for x in desc.splitlines()]) # concatenate lines
            desc = desc.strip()                                     # remove leading spaces
        else:
            desc = "NO DOCSTRING"

        s += "   {} @ {}\n".format(link,desc.lstrip())

    return s+'\n'