Exemplo n.º 1
0
def _get_other_member_doc(
    obj: Any,
    parser_config: config.ParserConfig,
    extra_docs: Optional[Dict[int, str]],
) -> str:
    """Returns the docs for other members of a module."""

    # An object's __doc__ attribute will mask the class'.
    my_doc = inspect.getdoc(obj)
    class_doc = inspect.getdoc(type(obj))

    description = None
    if my_doc != class_doc:
        # If they're different it's because __doc__ is set on the instance.
        if my_doc is not None:
            description = my_doc

    if description is None and extra_docs is not None:
        description = extra_docs.get(id(obj), None)

    info = None
    if isinstance(obj, dict):
        # pprint.pformat (next block) doesn't sort dicts until python 3.8
        items = [
            f' {name!r}: {value!r}'
            for name, value in sorted(obj.items(), key=repr)
        ]
        items = ',\n'.join(items)
        info = f'```\n{{\n{items}\n}}\n```'

    elif isinstance(obj, (set, frozenset)):
        # pprint.pformat (next block) doesn't sort dicts until python 3.8
        items = [f' {value!r}' for value in sorted(obj, key=repr)]
        items = ',\n'.join(items)
        info = f'```\n{{\n{items}\n}}\n```'
    elif (doc_generator_visitor.maybe_singleton(obj)
          or isinstance(obj, (list, tuple, enum.Enum))):
        # * Use pformat instead of repr so dicts and sets are sorted (deterministic)
        # * Escape ` so it doesn't break code formatting. You can't use "`"
        #   here since it will diaplay as a literal. I'm not sure why <pre></pre>
        #   breaks on the site.
        info = pprint.pformat(obj).replace('`', r'\`')
        info = f'`{info}`'
    elif obj_type_lib.ObjType.get(obj) is obj_type_lib.ObjType.PROPERTY:
        info = None
    else:
        class_full_name = parser_config.reverse_index.get(id(type(obj)), None)
        if class_full_name is None:
            module = getattr(type(obj), '__module__', None)
            class_name = type(obj).__name__
            if module is None or module == 'builtins':
                class_full_name = class_name
            else:
                class_full_name = f'{module}.{class_name}'
        info = f'Instance of `{class_full_name}`'

    parts = [info, description]
    parts = [item for item in parts if item is not None]

    return '\n\n'.join(parts)
Exemplo n.º 2
0
def _tfrepr(obj, parser_config):
    """Convert an object to a string for display."""
    info = None

    if isinstance(obj, dict):
        # pprint.pformat (next block) doesn't sort dicts until python 3.8
        items = [
            f' {name!r}: {value!r}'
            for name, value in sorted(obj.items(), key=repr)
        ]
        items = ',\n'.join(items)
        info = f'```\n{{\n{items}\n}}\n```'

    elif isinstance(obj, (set, frozenset)):
        # pprint.pformat (next block) doesn't sort dicts until python 3.8
        items = [f' {value!r}' for value in sorted(obj, key=repr)]
        items = ',\n'.join(items)
        info = f'```\n{{\n{items}\n}}\n```'
    elif (doc_generator_visitor.maybe_singleton(obj)
          or isinstance(obj, (list, tuple, enum.Enum))):
        # * Use pformat instead of repr so dicts and sets are sorted (deterministic)
        # * Escape ` so it doesn't break code formatting. You can't use "&#96;"
        #   here since it will diaplay as a literal. I'm not sure why <pre></pre>
        #   breaks on the site.
        info = pprint.pformat(obj).replace('`', r'\`')
        info = f'`{info}`'
    elif obj_type_lib.ObjType.get(obj) is obj_type_lib.ObjType.PROPERTY:
        info = None
    else:
        class_full_name = parser_config.reverse_index.get(id(type(obj)), None)
        if class_full_name is None:
            module = getattr(type(obj), '__module__', None)
            class_name = type(obj).__name__
            if module is None or module == 'builtins':
                class_full_name = class_name
            else:
                class_full_name = f'{module}.{class_name}'
        info = f'Instance of `{class_full_name}`'

    if info is not None:
        info = signature_lib.strip_obj_addresses(info)

    return info
Exemplo n.º 3
0
def _other_members(other_members):
  """Returns "other_members" rendered to markdown.

  `other_members` is used for anything that is not a class, function, module,
  or method.

  Args:
    other_members: a list of (name, object) pairs.

  Returns:
    A markdown string
  """
  parts = []
  list_item = '* `{short_name}` <a id="{short_name}"></a>\n'
  list_item_with_value = ('* `{short_name} = {obj!r}` '
                          '<a id="{short_name}"></a>\n')
  for other_member in other_members:
    if doc_generator_visitor.maybe_singleton(other_member.obj):
      part = list_item_with_value.format(**other_member._asdict())
    else:
      part = list_item.format(**other_member._asdict())
    parts.append(part)

  return ''.join(parts)
Exemplo n.º 4
0
# ==============================================================================
"""Visitor restricting traversal to only the public tensorflow API."""

import ast
import inspect
import os
import pathlib
import typing
from typing import Any, Callable, List, Sequence, Tuple

from tensorflow_docs.api_generator import doc_controls
from tensorflow_docs.api_generator import doc_generator_visitor

TYPING_IDS = frozenset(
    id(obj) for obj in typing.__dict__.values()
    if not doc_generator_visitor.maybe_singleton(obj))

Children = List[Tuple[str, Any]]
ApiFilter = Callable[[Tuple[str, ...], Any, Children], Children]


def get_module_base_dirs(module) -> Tuple[pathlib.Path, ...]:
    """Returns the list of base_dirs.

  Args:
    module: A python module object.

  Returns:
    A tuple of paths. Usually 1 unless the module is a namespace package.
  """
    if not hasattr(module, '__file__'):