PK!0s$ $ HISTORY.rstHistory ======= 1.2.3 (2019-01-31) ------------------ - Improve layout for stub generation with one-line class stubs. 1.2.2 (2019-01-08) ------------------ - Fix stub generation for superclass declarations with multiple dots. 1.2.1 (2018-12-27) ------------------ - Fix problem with function decorators that have parameters. - Switch to poetry for project management. 1.2 (2018-10-19) ---------------- - Generate stub files that follow the same layout as Black. - Fixed stub generation for async functions with decorators. 1.1 (2018-05-25) ---------------- - Added support for generating async function stubs. 1.0 (2018-05-25) ---------------- - Include type alias expansion in parameter type docstring. 1.0b9 (2018-03-23) ------------------ - Fixed bug about missing newlines after type aliases. 1.0b8 (2018-03-23) ------------------ - Added simplistic support for defining type aliases. 1.0b7 (2018-01-18) ------------------ - Added support for getting class signature from init method in Sphinx. 1.0b6 (2017-07-26) ------------------ - Fixed handling of * separator for keyword-only arguments. - Added support for keyword-only arguments with default values. - Added --version option to command line arguments. 1.0b5 (2017-07-26) ------------------ - Added support for property, staticmethod, and classmethod decorators. - Added support for keyword-only arguments. 1.0b4 (2017-06-16) ------------------ - Collect builtin types from the builtins module. 1.0b3 (2017-06-16) ------------------ - Fixes for ``*args`` and ``**kwargs`` on Python 2 code. 1.0b2 (2017-05-26) ------------------ - Added support for Python 2 again. 1.0b1 (2017-05-09) ------------------ - Added support for using type hints in Sphinx autodoc. 1.0a6 (2017-03-06) ------------------ - Improvements on imported names. 1.0a5 (2017-02-07) ------------------ - Support for methods. - Support for instance variables. - Support for base classes. - Shortened the field name from "signature" to "sig". - Use three dots instead of actual value for parameter defaults. - Dropped support for Python 2. 1.0a4 (2017-01-06) ------------------ - Long stubs are now spread over multiple lines. - Better handling of parameter defaults that are tuples. - Bugfix: handling of parameter defaults that have the value None. 1.0a3 (2017-01-06) ------------------ - Proper support for names from the typing module in input parameters. - Added parameter default values to stubs. 1.0a2 (2017-01-03) ------------------ - Support for Python 2.7. 1.0a1 (2017-01-03) ------------------ - First release on PyPI. PK!)|cc docs/Makefile# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SPHINXPROJ = pygenstub SOURCEDIR = source BUILDDIR = build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) PK!docs/source/_static/custom.cssPK!}dFFdocs/source/api.rstAPI === .. automodule:: pygenstub :members: :show-inheritance: PK!idocs/source/conf.py#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # pygenstub documentation build configuration file, created by # sphinx-quickstart on Tue Feb 7 17:50:37 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.1' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'pygenstub' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = 'pygenstub' copyright = '2017-2019, H. Turgut Uyar' author = 'H. Turgut Uyar' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.2' # The full version, including alpha/beta/rc tags. release = '1.2' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'pygenstubdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'pygenstub.tex', 'pygenstub Documentation', 'H. Turgut Uyar', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'pygenstub', 'pygenstub Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'pygenstub', 'pygenstub Documentation', author, 'pygenstub', 'One line description of project.', 'Miscellaneous'), ] PK!+(docs/source/features.rstFeatures ======== This document describes how pygenstub generates the stub files from the source. Methods ------- Methods are handled the same way as functions except that there is no type hint for the ``self`` parameter (assuming it's the first parameter): :code: .. code-block:: python class Foo: def foo(self, a): """Do foo. :sig: (int) -> None """ :stub: .. code-block:: python class Foo: def foo(self, a: int) -> None: ... Imported names -------------- Imported type names in the source will be used in the stub file *if needed*: :code: .. code-block:: python from x import A, B, C def foo(a, b): """Do foo. :sig: (A, B) -> A """ :stub: .. code-block:: python from x import A, B def foo(a: A, b: B) -> A: ... Note that the name ``C`` is not imported in the stub file. Qualified names --------------- Qualified (dotted) type names will generate import lines in the stub file if they are not already imported: :code: .. code-block:: python from z import x def foo(a, b): """Do foo. :sig: (x.A, y.B) -> m.n.C """ :stub: .. code-block:: python from z import x import y import m.n def foo(a: x.A, b: y.B) -> m.n.C: ... Names from the ``typing`` module -------------------------------- Unresolved names will be looked up in the ``typing`` module. :code: .. code-block:: python def foo(a, b): """Do foo. :sig: (List[int], Mapping[str, int]) -> Iterable[str] """ :stub: .. code-block:: python from typing import Iterable, List, Mapping def foo(a: List[int], b: Mapping[str, int]) -> Iterable[str]: ... Default values -------------- If a parameter has a default value, the prototype will contain the triple dots placeholder for it: :code: .. code-block:: python def foo(a, b=''): """Do foo. :sig: (int, Optional[str]) -> None """ :stub: .. code-block:: python from typing import Optional def foo(a: int, b: Optional[str] = ...) -> None: ... Base classes ------------ The imports needed for base classes will be included or generated using the same rules as described above (imported, dotted, etc.): :code: .. code-block:: python from x import A class Foo(A, y.B): def foo(self, a): """Do foo. :sig: (int) -> None """ :stub: .. code-block:: python from x import A import y class Foo(A, y.B): def foo(self, a: int) -> None: ... Class signatures ---------------- If the docstring of a class has a signature field, it will be used as the signature field of its ``__init__`` method unless that method already has a signature. :code: .. code-block:: python class Foo: """A foo. :sig: (int) -> None """ def __init__(self, a): self.a = a :stub: .. code-block:: python class Foo: def __init__(self, a: int) -> None: ... Signature comments ------------------ Type hints for assignments can be written using ``# sig:`` comments. :code: .. code-block:: python n = 42 # sig: int :stub: .. code-block:: python n = ... # type: int The rules for importing names as described above also apply here. .. note:: The reason for using ``# sig`` comment instead of a ``# type`` comment would be to avoid having to import the types. Instance variables ------------------ Within classes, assignments to attributes of ``self`` will generate assignments with type comments under the class: :code: .. code-block:: python class Foo: def foo(self): self.y = 'spam' # sig: str :stub: .. code-block:: python class Foo: y = ... # type: str Long lines ---------- If the prototype line gets too long, it will be divided into multiple lines: :code: .. code-block:: python def some_long_func_name(some_long_param_name_1, some_long_param_name_2): """Do foo. :sig: (some_long_type_1, some_long_type_2) -> some_long_type_3 """ :stub: .. code-block:: python def some_long_func_name( some_long_param_name_1: some_long_type_1, some_long_param_name_2: some_long_type_2, ) -> some_long_type_3: ... Type aliases ------------ Type aliases can be defined using a ``# sigalias`` comment: :code: .. code-block:: python # sigalias: A = int def foo(a): """Do foo. :sig: (A) -> None """ :stub: .. code-block:: python A = int def foo(a: A) -> None: ... PK!Ldocs/source/history.rst.. include:: ../../HISTORY.rst PK!>  docs/source/index.rstpygenstub ========= .. include:: ../../README.rst .. tip:: pygenstub can be used with PyCharm file watchers to update stub files automatically when source files are modified. .. toctree:: :maxdepth: 2 :caption: Contents: features api history PK!˛ll pygenstub.py# Copyright (C) 2016-2019 H. Turgut Uyar # # pygenstub is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # pygenstub is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with pygenstub. If not, see . """pygenstub is a utility for generating stub files from docstrings in source files. It takes a source file as input and creates a stub file with the same base name and the ``.pyi`` extension. For more information, please refer to the documentation: https://pygenstub.readthedocs.io/ """ from __future__ import absolute_import, division, print_function, unicode_literals import ast import inspect import logging import re import sys import textwrap from argparse import ArgumentParser from bisect import bisect from collections import OrderedDict from io import StringIO from docutils.core import publish_doctree __version__ = "1.2.3" # sig: str PY3 = sys.version_info >= (3, 0) if not PY3: import __builtin__ as builtins from codecs import open else: import builtins # sigalias: Document = docutils.nodes.document BUILTIN_TYPES = {k for k, t in builtins.__dict__.items() if isinstance(t, type)} BUILTIN_TYPES.add("None") SIG_FIELD = "sig" # sig: str SIG_COMMENT = "# sig:" # sig: str SIG_ALIAS = "# sigalias:" # sig: str DECORATORS = {"property", "staticmethod", "classmethod"} # sig: Set[str] LINE_LENGTH_LIMIT = 79 INDENT = 4 * " " EDIT_WARNING = "THIS FILE IS AUTOMATICALLY GENERATED, DO NOT EDIT MANUALLY." _RE_QUALIFIED_TYPES = re.compile(r"\w+(?:\.\w+)*") _RE_COMMENT_IN_STRING = re.compile(r"""['"]\s*%(text)s\s*.*['"]""" % {"text": SIG_COMMENT}) _logger = logging.getLogger(__name__) def get_fields(node, fields_tag="field_list"): """Get the field names and their values from a node. :sig: (Document, Optional[str]) -> Dict[str, str] :param node: Node to get the fields from. :param fields_tag: Tag of child node that contains the fields. :return: Names and values of fields. """ fields_nodes = [c for c in node.children if c.tagname == fields_tag] if len(fields_nodes) == 0: return {} assert len(fields_nodes) == 1, "multiple nodes with tag " + fields_tag fields_node = fields_nodes[0] fields = [ {f.tagname: f.rawsource.strip() for f in n.children} for n in fields_node.children if n.tagname == "field" ] return {f["field_name"]: f["field_body"] for f in fields} def extract_signature(docstring): """Extract the signature from a docstring. :sig: (str) -> Optional[str] :param docstring: Docstring to extract the signature from. :return: Extracted signature, or ``None`` if there's no signature. """ root = publish_doctree(docstring, settings_overrides={"report_level": 5}) fields = get_fields(root) return fields.get(SIG_FIELD) def get_signature(node): """Get the signature of a function or a class. :sig: (Union[ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef]) -> Optional[str] :param node: Node to get the signature from. :return: Value of signature field in node docstring, or ``None`` if there's no signature. """ docstring = ast.get_docstring(node) if docstring is None: return None return extract_signature(docstring) def split_parameter_types(parameters): """Split a parameter types declaration into individual types. The input is the left hand side of a signature (the part before the arrow), excluding the parentheses. :sig: (str) -> List[str] :param parameters: Comma separated parameter types. :return: Parameter types. """ if parameters == "": return [] # only consider the top level commas, ignore the ones in [] commas = [] bracket_depth = 0 for i, char in enumerate(parameters): if (char == ",") and (bracket_depth == 0): commas.append(i) elif char == "[": bracket_depth += 1 elif char == "]": bracket_depth -= 1 types = [] last_i = 0 for i in commas: types.append(parameters[last_i:i].strip()) last_i = i + 1 else: types.append(parameters[last_i:].strip()) return types def parse_signature(signature): """Parse a signature into its input and return parameter types. This will also collect the types that are required by any of the input and return types. :sig: (str) -> Tuple[List[str], str, Set[str]] :param signature: Signature to parse. :return: Input parameter types, return type, and all required types. """ if " -> " not in signature: # signature comment: no parameters, treat variable type as return type param_types, return_type = None, signature.strip() else: lhs, return_type = [s.strip() for s in signature.split(" -> ")] csv = lhs[1:-1].strip() # remove the parentheses around the parameter type list param_types = split_parameter_types(csv) requires = set(_RE_QUALIFIED_TYPES.findall(signature)) return param_types, return_type, requires class StubNode: """A node in a stub tree.""" def __init__(self): """Initialize this stub node. :sig: () -> None """ self.variables = [] # sig: List[VariableNode] self.children = [] # sig: List[Union[FunctionNode, ClassNode]] self.parent = None # sig: Optional[StubNode] def add_variable(self, node): """Add a variable node to this node. :sig: (VariableNode) -> None :param node: Variable node to add. """ self.variables.append(node) node.parent = self def add_child(self, node): """Add a function/method or class node to this node. :sig: (Union[FunctionNode, ClassNode]) -> None :param node: Function or class node to add. """ self.children.append(node) node.parent = self def get_code(self): """Get the stub code for this node. The stub code for a node consists of the type annotations of its variables, followed by the prototypes of its functions/methods and classes. :sig: () -> List[str] :return: Lines of stub code for this node. """ stub = [] for child in self.variables: stub.extend(child.get_code()) if ( (len(self.variables) > 0) and (len(self.children) > 0) and (not isinstance(self, ClassNode)) ): stub.append("") for child in self.children: stub.extend(child.get_code()) return stub class VariableNode(StubNode): """A node representing an assignment in a stub tree.""" def __init__(self, name, type_): """Initialize this variable node. :sig: (str, str) -> None :param name: Name of variable that is being assigned to. :param type_: Type of variable. """ if not PY3: StubNode.__init__(self) else: super().__init__() self.name = name # sig: str self.type_ = type_ # sig: str def get_code(self): """Get the type annotation for this variable. :sig: () -> List[str] :return: Lines of stub code for this variable. """ return ["%(n)s = ... # type: %(t)s" % {"n": self.name, "t": self.type_}] class FunctionNode(StubNode): """A node representing a function in a stub tree.""" def __init__(self, name, parameters, rtype, decorators=None): """Initialize this function node. The parameters have to given as a list of triples where each item specifies the name of the parameter, its type, and whether it has a default value or not. :sig: (str, Sequence[Tuple[str, str, bool]], str, Optional[Sequence[str]]) -> None :param name: Name of function. :param parameters: List of parameter triples (name, type, has_default). :param rtype: Type of return value. :param decorators: Decorators of function. """ if not PY3: StubNode.__init__(self) else: super().__init__() self.name = name # sig: str self.parameters = parameters # sig: Sequence[Tuple[str, str, bool]] self.rtype = rtype # sig: str self.decorators = decorators if decorators is not None else [] # sig: Sequence[str] self._async = False # sig: bool def get_code(self): """Get the stub code for this function. :sig: () -> List[str] :return: Lines of stub code for this function. """ stub = [] for deco in self.decorators: if (deco in DECORATORS) or deco.endswith(".setter"): stub.append("@" + deco) parameters = [] for name, type_, has_default in self.parameters: decl = "%(n)s%(t)s%(d)s" % { "n": name, "t": ": " + type_ if type_ else "", "d": " = ..." if has_default else "", } parameters.append(decl) slots = { "a": "async " if self._async else "", "n": self.name, "p": ", ".join(parameters), "r": self.rtype, } prototype = "%(a)sdef %(n)s(%(p)s) -> %(r)s: ..." % slots if len(prototype) <= LINE_LENGTH_LIMIT: stub.append(prototype) elif len(INDENT + slots["p"]) <= LINE_LENGTH_LIMIT: stub.append("%(a)sdef %(n)s(" % slots) stub.append(INDENT + slots["p"]) stub.append(") -> %(r)s: ..." % slots) else: stub.append("%(a)sdef %(n)s(" % slots) for param in parameters: stub.append(INDENT + param + ",") stub.append(") -> %(r)s: ..." % slots) return stub class ClassNode(StubNode): """A node representing a class in a stub tree.""" def __init__(self, name, bases, signature=None): """Initialize this class node. :sig: (str, Sequence[str], Optional[str]) -> None :param name: Name of class. :param bases: Base classes of class. :param signature: Signature of class, to be used in __init__ method. """ if not PY3: StubNode.__init__(self) else: super().__init__() self.name = name # sig: str self.bases = bases # sig: Sequence[str] self.signature = signature # sig: Optional[str] def get_code(self): """Get the stub code for this class. :sig: () -> List[str] :return: Lines of stub code for this class. """ stub = [] bases = ("(" + ", ".join(self.bases) + ")") if len(self.bases) > 0 else "" slots = {"n": self.name, "b": bases} if len(self.children) == 0: stub.append("class %(n)s%(b)s: ..." % slots) else: stub.append("class %(n)s%(b)s:" % slots) super_code = super().get_code() if PY3 else StubNode.get_code(self) for line in super_code: stub.append(INDENT + line) return stub def get_aliases(lines): """Get the type aliases in the source. :sig: (Sequence[str]) -> Dict[str, str] :param lines: Lines of the source code. :return: Aliases and their their definitions. """ aliases = {} for line in lines: line = line.strip() if len(line) > 0 and line.startswith(SIG_ALIAS): _, content = line.split(SIG_ALIAS) alias, signature = [t.strip() for t in content.split("=")] aliases[alias] = signature return aliases class StubGenerator(ast.NodeVisitor): """A transformer that generates stub declarations from a source code.""" def __init__(self, source): """Initialize this stub generator. :sig: (str) -> None :param source: Source code to generate the stub for. """ self.root = StubNode() # sig: StubNode self.imported_names = OrderedDict() # sig: OrderedDict[str, str] self.defined_types = set() # sig: Set[str] self.required_types = set() # sig: Set[str] self.aliases = OrderedDict() # sig: OrderedDict[str, str] self._parents = [self.root] # sig: List[StubNode] self._code_lines = source.splitlines() # sig: List[str] self.collect_aliases() ast_tree = ast.parse(source) self.visit(ast_tree) def collect_aliases(self): """Collect the type aliases in the source. :sig: () -> None """ self.aliases = get_aliases(self._code_lines) for alias, signature in self.aliases.items(): _, _, requires = parse_signature(signature) self.required_types |= requires self.defined_types |= {alias} def visit_ImportFrom(self, node): """Process a "from x import y" node. :sig: (ast.ImportFrom) -> None :param node: Node to process. """ line = self._code_lines[node.lineno - 1] module_name = line.split("from")[1].split("import")[0].strip() for name in node.names: self.imported_names[name.name] = module_name def visit_Assign(self, node): """Process an assignment node. :sig: (ast.Assign) -> None :param node: Node to process. """ line = self._code_lines[node.lineno - 1] if SIG_COMMENT in line: line = _RE_COMMENT_IN_STRING.sub("", line) if SIG_COMMENT in line: _, signature = line.split(SIG_COMMENT) _, return_type, requires = parse_signature(signature) self.required_types |= requires parent = self._parents[-1] for var in node.targets: if isinstance(var, ast.Name): stub_node = VariableNode(var.id, return_type) parent.add_variable(stub_node) if isinstance(var, ast.Attribute) and (var.value.id == "self"): stub_node = VariableNode(var.attr, return_type) parent.parent.add_variable(stub_node) def get_function_node(self, node): """Process a function node. :sig: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> FunctionNode :param node: Node to process. :return: Generated function node in stub tree. """ signature = get_signature(node) if signature is None: parent = self._parents[-1] if isinstance(parent, ClassNode) and (node.name == "__init__"): signature = parent.signature if signature is not None: _logger.debug("parsing signature for %s", node.name) param_types, rtype, requires = parse_signature(signature) _logger.debug("parameter types: %s", param_types) _logger.debug("return type: %s", rtype) _logger.debug("required types: %s", requires) self.required_types |= requires decorators = [] for d in node.decorator_list: if hasattr(d, "id"): decorators.append(d.id) elif hasattr(d, "func"): decorators.append(d.func.id) elif hasattr(d, "value"): decorators.append(d.value.id + "." + d.attr) param_names = [arg.arg if PY3 else arg.id for arg in node.args.args] # TODO: only in classes if (len(param_names) > 0) and (param_names[0] == "self"): param_types.insert(0, "") # TODO: only in classes if ( (len(param_names) > 0) and (param_names[0] == "cls") and ("classmethod" in decorators) ): param_types.insert(0, "") if node.args.vararg is not None: param_names.append("*" + (node.args.vararg.arg if PY3 else node.args.vararg)) param_types.append("") if node.args.kwarg is not None: param_names.append("**" + (node.args.kwarg.arg if PY3 else node.args.kwarg)) param_types.append("") n_args = len(param_names) kwonly_args = getattr(node.args, "kwonlyargs", []) if len(kwonly_args) > 0: param_names.extend([arg.arg for arg in kwonly_args]) if len(param_types) != len(param_names): raise ValueError("Parameter names and types don't match: " + node.name) param_locs = [(a.lineno, a.col_offset) for a in (node.args.args + kwonly_args)] param_defaults = { bisect(param_locs, (d.lineno, d.col_offset)) - 1 for d in node.args.defaults } kwonly_defaults = getattr(node.args, "kw_defaults", []) for i, d in enumerate(kwonly_defaults): if d is not None: param_defaults.add(n_args + i) params = [ (name, type_, i in param_defaults) for i, (name, type_) in enumerate(zip(param_names, param_types)) ] if len(kwonly_args) > 0: params.insert(n_args, ("*", "", False)) stub_node = FunctionNode( node.name, parameters=params, rtype=rtype, decorators=decorators ) self._parents[-1].add_child(stub_node) self._parents.append(stub_node) self.generic_visit(node) del self._parents[-1] return stub_node def visit_FunctionDef(self, node): """Process a regular function node. :sig: (ast.FunctionDef) -> None :param node: Node to process. """ node = self.get_function_node(node) if node is not None: node._async = False def visit_AsyncFunctionDef(self, node): """Process an async function node. :sig: (ast.AsyncFunctionDef) -> None :param node: Node to process. """ node = self.get_function_node(node) if node is not None: node._async = True def visit_ClassDef(self, node): """Process a class node. :sig: (ast.ClassDef) -> None :param node: Node to process. """ self.defined_types.add(node.name) bases = [] for n in node.bases: base_parts = [] while True: if not isinstance(n, ast.Attribute): base_parts.append(n.id) break else: base_parts.append(n.attr) n = n.value bases.append(".".join(base_parts[::-1])) self.required_types |= set(bases) signature = get_signature(node) stub_node = ClassNode(node.name, bases=bases, signature=signature) self._parents[-1].add_child(stub_node) self._parents.append(stub_node) self.generic_visit(node) del self._parents[-1] @staticmethod def generate_import(module_, names): """Generate an import line. :sig: (str, Set[str]) -> str :param module_: Name of module to import the names from. :param names: Names to import. :return: Import line in stub code. """ slots = {"m": module_, "n": ", ".join(sorted(names))} line = "from %(m)s import %(n)s" % slots if len(line) > LINE_LENGTH_LIMIT: slots["n"] = INDENT + (",\n" + INDENT).join(sorted(names)) + "," line = "from %(m)s import (\n%(n)s\n)" % slots return line def generate_stub(self): """Generate the stub code for this source. :sig: () -> str :return: Generated stub code. """ needed_types = self.required_types - BUILTIN_TYPES needed_types -= self.defined_types _logger.debug("defined types: %s", self.defined_types) module_vars = {v.name for v in self.root.variables} _logger.debug("module variables: %s", module_vars) qualified_types = {n for n in needed_types if "." in n} qualified_namespaces = {".".join(n.split(".")[:-1]) for n in qualified_types} needed_namespaces = qualified_namespaces - module_vars needed_types -= qualified_types _logger.debug("needed namespaces: %s", needed_namespaces) imported_names = set(self.imported_names) imported_types = imported_names & (needed_types | needed_namespaces) needed_types -= imported_types needed_namespaces -= imported_names _logger.debug("used imported types: %s", imported_types) try: typing_mod = __import__("typing") typing_types = {n for n in needed_types if hasattr(typing_mod, n)} needed_types -= typing_types _logger.debug("types from typing module: %s", typing_types) except ImportError: typing_types = set() _logger.warn("typing module not installed") if len(needed_types) > 0: raise ValueError("Unknown types: " + ", ".join(needed_types)) out = StringIO() started = False if len(typing_types) > 0: line = self.generate_import("typing", typing_types) out.write(line + "\n") started = True if len(imported_types) > 0: if started: out.write("\n") # preserve the import order in the source file for name in self.imported_names: if name in imported_types: line = self.generate_import(self.imported_names[name], {name}) out.write(line + "\n") started = True if len(needed_namespaces) > 0: if started: out.write("\n") for module_ in sorted(needed_namespaces): out.write("import " + module_ + "\n") started = True if len(self.aliases) > 0: if started: out.write("\n") for alias, signature in self.aliases.items(): out.write("%s = %s\n" % (alias, signature)) started = True if started: out.write("\n") stub_lines = self.root.get_code() prev_line = None for line in stub_lines: if line.startswith("class ") and prev_line and (not prev_line.startswith("class ")): out.write("\n") if ( line.startswith("def ") and prev_line and (prev_line.startswith(" ") or prev_line.startswith("class ")) ): out.write("\n") out.write(line + "\n") prev_line = line return out.getvalue() def get_stub(source): """Get the stub code for a source code. :sig: (str) -> str :param source: Source code to generate the stub for. :return: Generated stub code. """ generator = StubGenerator(source) stub = generator.generate_stub() return stub def process_docstring(app, what, name, obj, options, lines): """Modify the docstring before generating documentation. This will insert type declarations for parameters and return type into the docstring, and remove the signature field so that it will be excluded from the generated document. """ aliases = getattr(app, "_sigaliases", None) if aliases is None: if what == "module": aliases = get_aliases(inspect.getsource(obj).splitlines()) app._sigaliases = aliases sig_marker = ":" + SIG_FIELD + ":" is_class = what in ("class", "exception") signature = extract_signature("\n".join(lines)) if signature is None: if not is_class: return init_method = getattr(obj, "__init__") init_doc = init_method.__doc__ init_lines = init_doc.splitlines()[1:] if len(init_lines) > 1: init_doc = textwrap.dedent("\n".join(init_lines[1:])) init_lines = init_doc.splitlines() if sig_marker not in init_doc: return sig_started = False for line in init_lines: if line.lstrip().startswith(sig_marker): sig_started = True if sig_started: lines.append(line) signature = extract_signature("\n".join(lines)) if is_class: obj = init_method param_types, rtype, _ = parse_signature(signature) param_names = [p for p in inspect.signature(obj).parameters] if is_class and (param_names[0] == "self"): del param_names[0] # if something goes wrong, don't insert parameter types if len(param_names) == len(param_types): for name, type_ in zip(param_names, param_types): find = ":param %(name)s:" % {"name": name} alias = aliases.get(type_) if alias is not None: type_ = "*%(type)s* :sup:`%(alias)s`" % {"type": type_, "alias": alias} for i, line in enumerate(lines): if line.startswith(find): lines.insert(i, ":type %(name)s: %(type)s" % {"name": name, "type": type_}) break if not is_class: for i, line in enumerate(lines): if line.startswith((":return:", ":returns:")): lines.insert(i, ":rtype: " + rtype) break # remove the signature field sig_start = 0 while sig_start < len(lines): if lines[sig_start].startswith(sig_marker): break sig_start += 1 sig_end = sig_start + 1 while sig_end < len(lines): if (not lines[sig_end]) or (lines[sig_end][0] != " "): break sig_end += 1 for i in reversed(range(sig_start, sig_end)): del lines[i] def setup(app): """Register the Sphinx extension.""" app.connect("autodoc-process-docstring", process_docstring) return dict(parallel_read_safe=True) def main(argv=None): """Entry point of the command-line utility. :sig: (Optional[List[str]]) -> None :param argv: Command line arguments. """ argv = argv if argv is not None else sys.argv parser = ArgumentParser(prog="pygenstub") parser.add_argument("--version", action="version", version="%(prog)s " + __version__) parser.add_argument("source", help="source file") parser.add_argument("--debug", action="store_true", help="enable debug messages") arguments = parser.parse_args(argv[1:]) # set debug mode if arguments.debug: logging.basicConfig(level=logging.DEBUG) _logger.debug("running in debug mode") with open(arguments.source, mode="r", encoding="utf-8") as f_in: code = f_in.read() try: stub = get_stub(code) except RuntimeError as e: print(e, file=sys.stderr) sys.exit(1) if stub != "": destination = arguments.source + "i" with open(destination, mode="w", encoding="utf-8") as f_out: f_out.write("# " + EDIT_WARNING + "\n\n") f_out.write(stub) if __name__ == "__main__": main() PK!q pygenstub.pyi# THIS FILE IS AUTOMATICALLY GENERATED, DO NOT EDIT MANUALLY. from typing import Dict, List, Optional, Sequence, Set, Tuple, Union from collections import OrderedDict import ast import docutils.nodes Document = docutils.nodes.document __version__ = ... # type: str SIG_FIELD = ... # type: str SIG_COMMENT = ... # type: str SIG_ALIAS = ... # type: str DECORATORS = ... # type: Set[str] def get_fields( node: Document, fields_tag: Optional[str] = ... ) -> Dict[str, str]: ... def extract_signature(docstring: str) -> Optional[str]: ... def get_signature( node: Union[ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef] ) -> Optional[str]: ... def split_parameter_types(parameters: str) -> List[str]: ... def parse_signature(signature: str) -> Tuple[List[str], str, Set[str]]: ... class StubNode: variables = ... # type: List[VariableNode] children = ... # type: List[Union[FunctionNode, ClassNode]] parent = ... # type: Optional[StubNode] def __init__(self) -> None: ... def add_variable(self, node: VariableNode) -> None: ... def add_child(self, node: Union[FunctionNode, ClassNode]) -> None: ... def get_code(self) -> List[str]: ... class VariableNode(StubNode): name = ... # type: str type_ = ... # type: str def __init__(self, name: str, type_: str) -> None: ... def get_code(self) -> List[str]: ... class FunctionNode(StubNode): name = ... # type: str parameters = ... # type: Sequence[Tuple[str, str, bool]] rtype = ... # type: str decorators = ... # type: Sequence[str] _async = ... # type: bool def __init__( self, name: str, parameters: Sequence[Tuple[str, str, bool]], rtype: str, decorators: Optional[Sequence[str]] = ..., ) -> None: ... def get_code(self) -> List[str]: ... class ClassNode(StubNode): name = ... # type: str bases = ... # type: Sequence[str] signature = ... # type: Optional[str] def __init__( self, name: str, bases: Sequence[str], signature: Optional[str] = ... ) -> None: ... def get_code(self) -> List[str]: ... def get_aliases(lines: Sequence[str]) -> Dict[str, str]: ... class StubGenerator(ast.NodeVisitor): root = ... # type: StubNode imported_names = ... # type: OrderedDict[str, str] defined_types = ... # type: Set[str] required_types = ... # type: Set[str] aliases = ... # type: OrderedDict[str, str] _parents = ... # type: List[StubNode] _code_lines = ... # type: List[str] def __init__(self, source: str) -> None: ... def collect_aliases(self) -> None: ... def visit_ImportFrom(self, node: ast.ImportFrom) -> None: ... def visit_Assign(self, node: ast.Assign) -> None: ... def get_function_node( self, node: Union[ast.FunctionDef, ast.AsyncFunctionDef] ) -> FunctionNode: ... def visit_FunctionDef(self, node: ast.FunctionDef) -> None: ... def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: ... def visit_ClassDef(self, node: ast.ClassDef) -> None: ... @staticmethod def generate_import(module_: str, names: Set[str]) -> str: ... def generate_stub(self) -> str: ... def get_stub(source: str) -> str: ... def main(argv: Optional[List[str]] = ...) -> None: ... PK![=tests/test_cli.pyfrom pytest import fixture, raises import logging import os import shutil import sys from pkg_resources import get_distribution import pygenstub @fixture def source(): """Python source code for testing.""" base_dir = os.path.dirname(__file__) src = os.path.join(base_dir, "..", "pygenstub.py") dst = "/dev/shm/foo.py" if sys.platform in {"linux", "linux2"} else "foo.py" shutil.copy(src, dst) yield src, dst os.unlink(dst) if os.path.exists(dst + "i"): os.unlink(dst + "i") def test_version_should_be_same_as_installed(): assert get_distribution("pygenstub").version == pygenstub.__version__ def test_cli_help_should_print_usage_and_exit(capsys): with raises(SystemExit): pygenstub.main(argv=["pygenstub", "--help"]) out, err = capsys.readouterr() assert out.startswith("usage: ") def test_cli_version_should_print_version_number_and_exit(capsys): with raises(SystemExit): pygenstub.main(argv=["pygenstub", "--version"]) out, err = capsys.readouterr() assert "pygenstub " + pygenstub.__version__ + "\n" in {out, err} def test_cli_no_input_file_should_print_usage_and_exit(capsys): with raises(SystemExit): pygenstub.main(argv=["pygenstub"]) out, err = capsys.readouterr() assert err.startswith("usage: ") assert ("required: source" in err) or ("too few arguments" in err) def test_cli_unrecognized_arguments_should_print_usage_and_exit(capsys): with raises(SystemExit): pygenstub.main(argv=["pygenstub", "--foo", "foo.py"]) out, err = capsys.readouterr() assert err.startswith("usage: ") assert "unrecognized arguments: --foo" in err def test_cli_debug_mode_should_print_debug_messages_on_stderr(caplog, source): caplog.set_level(logging.DEBUG) pygenstub.main(argv=["pygenstub", "--debug", source[1]]) assert caplog.record_tuples[0][-1] == "running in debug mode" def test_cli_original_module_should_generate_original_stub(source): pygenstub.main(argv=["pygenstub", source[1]]) with open(source[0] + "i") as src: src_stub = src.read() with open(source[1] + "i") as dst: dst_stub = dst.read() assert dst_stub == src_stub PK!AAtests/test_stub.pyfrom __future__ import unicode_literals from pytest import mark, raises import sys from io import StringIO from pygenstub import get_stub _INDENT = " " * 4 def get_function( name, desc="Do foo.", params=None, ptypes=None, rtype=None, decorators=None, body="pass" ): code = StringIO() if decorators is not None: code.write("\n".join(decorators) + "\n") pstr = ", ".join(params) if params is not None else "" code.write("def %(name)s(%(p)s):\n" % {"name": name, "p": pstr}) if desc: code.write(_INDENT + '"""%(desc)s\n\n' % {"desc": desc}) tstr = ", ".join(ptypes) if ptypes is not None else "" if rtype is not None: code.write(_INDENT + ":sig: (%(t)s) -> %(rtype)s\n" % {"t": tstr, "rtype": rtype}) code.write(_INDENT + '"""\n') code.write(_INDENT + body + "\n") return code.getvalue() def get_class(name, bases=None, desc="A foo.", sig=None, methods=None): code = StringIO() bstr = ("(" + ", ".join(bases) + ")") if bases is not None else "" code.write("class %(name)s%(bases)s:\n" % {"name": name, "bases": bstr}) if desc is not None: code.write(_INDENT + '"""%(desc)s\n\n' % {"desc": desc}) if sig is not None: code.write("\n" + _INDENT + ":sig: %(sig)s\n" % {"sig": sig}) code.write(_INDENT + '"""\n') if methods is not None: for method in methods: for line in method.splitlines(): code.write(_INDENT + line + "\n") else: code.write(_INDENT + "pass\n") return code.getvalue() def test_if_no_docstring_then_stub_should_be_empty(): code = get_function("f", desc="") assert get_stub(code) == "" def test_if_no_sig_then_stub_should_be_empty(): code = get_function("f") assert get_stub(code) == "" def test_if_returns_none_then_stub_should_return_none(): code = get_function("f", rtype="None") assert get_stub(code) == "def f() -> None: ...\n" def test_if_returns_builtin_then_stub_should_return_builtin(): code = get_function("f", rtype="int") assert get_stub(code) == "def f() -> int: ...\n" def test_if_returns_from_imported_then_stub_should_include_import(): code = "from x import A\n" code += "\n\n" + get_function("f", rtype="A") assert get_stub(code) == "from x import A\n\ndef f() -> A: ...\n" def test_stub_should_exclude_unused_import(): code = "from x import A, B\n" code += "\n\n" + get_function("f", rtype="A") assert get_stub(code) == "from x import A\n\ndef f() -> A: ...\n" # def test_stub_should_include_all_used_imports(): # code = "from x import A, B\n" # code += "\n\n" + get_function("f", rtype="A") # code += "\n\n" + get_function("g", rtype="B") # assert get_stub(code) == "from x import A, B\n\ndef f() -> A: ...\ndef g() -> B: ...\n" def test_if_returns_imported_qualified_then_stub_should_include_import(): code = "import x\n" code += "\n\n" + get_function("f", rtype="x.A") assert get_stub(code) == "import x\n\ndef f() -> x.A: ...\n" def test_if_returns_from_imported_qualified_then_stub_should_include_import(): code = "from x import y\n" code += "\n\n" + get_function("f", rtype="y.A") assert get_stub(code) == "from x import y\n\ndef f() -> y.A: ...\n" def test_if_returns_relative_imported_qualified_then_stub_should_include_import(): code = "from . import x\n" code += "\n\n" + get_function("f", rtype="x.A") assert get_stub(code) == "from . import x\n\ndef f() -> x.A: ...\n" def test_if_returns_unimported_qualified_then_stub_should_generate_import(): code = get_function("f", rtype="x.y.A") assert get_stub(code) == "import x.y\n\ndef f() -> x.y.A: ...\n" def test_if_returns_imported_typing_then_stub_should_include_import(): code = "from typing import List\n" code += "\n\n" + get_function("f", rtype="List") assert get_stub(code) == "from typing import List\n\ndef f() -> List: ...\n" def test_if_returns_unimported_typing_then_stub_should_generate_import(): code = get_function("f", rtype="List") assert get_stub(code) == "from typing import List\n\ndef f() -> List: ...\n" def test_if_returns_qualified_typing_then_stub_should_return_qualified_typing(): code = get_function("f", rtype="List[str]") assert get_stub(code) == "from typing import List\n\ndef f() -> List[str]: ...\n" def test_if_returns_multiple_typing_then_stub_should_generate_multiple_import(): code = get_function("f", rtype="Dict[str, Any]") assert get_stub(code) == "from typing import Any, Dict\n\ndef f() -> Dict[str, Any]: ...\n" def test_if_returns_unknown_type_should_raise_error(): code = get_function("f", rtype="Foo") with raises(ValueError) as e: get_stub(code) assert "Unknown types: Foo" in str(e) def test_if_one_param_then_stub_should_have_one_param(): code = get_function("f", params=["i"], ptypes=["int"], rtype="None") assert get_stub(code) == "def f(i: int) -> None: ...\n" def test_if_multiple_params_then_stub_should_have_multiple_params(): code = get_function("f", params=["i", "s"], ptypes=["int", "str"], rtype="None") assert get_stub(code) == "def f(i: int, s: str) -> None: ...\n" def test_if_param_type_imported_then_stub_should_include_import(): code = "from x import A\n" code += "\n\n" + get_function("f", params=["a"], ptypes=["A"], rtype="None") assert get_stub(code) == "from x import A\n\ndef f(a: A) -> None: ...\n" def test_if_param_type_from_imported_then_stub_should_include_import(): code = "from x import A\n" code += "\n\n" + get_function("f", params=["a"], ptypes=["A"], rtype="None") assert get_stub(code) == "from x import A\n\ndef f(a: A) -> None: ...\n" def test_if_param_type_imported_qualified_then_stub_should_include_import(): code = "import x\n" code += "\n\n" + get_function("f", params=["a"], ptypes=["x.A"], rtype="None") assert get_stub(code) == "import x\n\ndef f(a: x.A) -> None: ...\n" def test_if_param_type_from_imported_qualified_then_stub_should_include_import(): code = "from x import y\n" code += get_function("f", params=["a"], ptypes=["y.A"], rtype="None") assert get_stub(code) == "from x import y\n\ndef f(a: y.A) -> None: ...\n" def test_if_param_type_relative_imported_qualified_then_stub_should_include_import(): code = "from . import x\n" code += "\n\n" + get_function("f", params=["a"], ptypes=["x.A"], rtype="None") assert get_stub(code) == "from . import x\n\ndef f(a: x.A) -> None: ...\n" def test_if_param_type_unimported_qualified_then_stub_should_generate_import(): code = get_function("f", params=["a"], ptypes=["x.y.A"], rtype="None") assert get_stub(code) == "import x.y\n\ndef f(a: x.y.A) -> None: ...\n" def test_if_param_type_imported_typing_then_stub_should_include_import(): code = "from typing import List\n" code += "\n\n" + get_function("f", params=["l"], ptypes=["List"], rtype="None") assert get_stub(code) == "from typing import List\n\ndef f(l: List) -> None: ...\n" def test_if_param_type_unimported_typing_then_stub_should_include_import(): code = get_function("f", params=["l"], ptypes=["List"], rtype="None") assert get_stub(code) == "from typing import List\n\ndef f(l: List) -> None: ...\n" def test_if_param_type_qualified_typing_then_stub_should_include_qualified_typing(): code = get_function("f", params=["ls"], ptypes=["List[str]"], rtype="None") assert get_stub(code) == "from typing import List\n\ndef f(ls: List[str]) -> None: ...\n" def test_if_param_type_multiple_typing_then_stub_should_include_multiple_import(): code = get_function("f", params=["d"], ptypes=["Dict[str, Any]"], rtype="None") assert ( get_stub(code) == "from typing import Any, Dict\n\ndef f(d: Dict[str, Any]) -> None: ...\n" ) def test_if_param_type_unknown_should_raise_error(): code = get_function("f", params=["i"], ptypes=["Foo"], rtype="None") with raises(ValueError) as e: get_stub(code) assert "Unknown types: Foo" in str(e) def test_if_param_has_default_then_stub_should_include_ellipses(): code = get_function("f", params=["i=0"], ptypes=["Optional[int]"], rtype="None") assert ( get_stub(code) == "from typing import Optional\n\ndef f(i: Optional[int] = ...) -> None: ...\n" ) def test_stub_should_ignore_varargs_type(): code = get_function("f", params=["i", "*args"], ptypes=["int"], rtype="None") assert get_stub(code) == "def f(i: int, *args) -> None: ...\n" def test_stub_should_ignore_kwargs_type(): code = get_function("f", params=["i", "**kwargs"], ptypes=["int"], rtype="None") assert get_stub(code) == "def f(i: int, **kwargs) -> None: ...\n" def test_stub_should_ignore_vararg_and_kwargs_types(): code = get_function("f", params=["i", "*args", "**kwargs"], ptypes=["int"], rtype="None") assert get_stub(code) == "def f(i: int, *args, **kwargs) -> None: ...\n" @mark.skipif(sys.version_info < (3, 0), reason="syntax introduced in py3") def test_stub_should_honor_kwonly_args(): code = get_function("f", params=["i", "*", "j"], ptypes=["int", "int"], rtype="None") assert get_stub(code) == "def f(i: int, *, j: int) -> None: ...\n" @mark.skipif(sys.version_info < (3, 0), reason="syntax introduced in py3") def test_stub_should_honor_kwonly_args_with_default(): code = get_function( "f", params=["i", "*", "j=0"], ptypes=["int", "Optional[int]"], rtype="None" ) assert ( get_stub(code) == "from typing import Optional\n\ndef f(i: int, *, j: Optional[int] = ...) -> None: ...\n" ) def test_missing_types_should_raise_error(): code = get_function("f", params=["i", "j"], ptypes=["int"], rtype="None") with raises(ValueError) as e: get_stub(code) assert "Parameter names and types don't match: " in str(e) def test_extra_types_should_raise_error(): code = get_function("f", params=["i"], ptypes=["int", "int"], rtype="None") with raises(ValueError) as e: get_stub(code) assert "Parameter names and types don't match: " in str(e) def test_if_function_decorated_unknown_then_stub_should_ignore(): code = get_function("f", rtype="None", decorators=["@foo"]) assert get_stub(code) == "def f() -> None: ...\n" def test_if_function_decorated_callable_unknown_then_stub_should_ignore(): code = get_function("f", rtype="None", decorators=["@foo()"]) assert get_stub(code) == "def f() -> None: ...\n" def test_stub_should_include_empty_class(): code = get_class("C") assert get_stub(code) == "class C: ...\n" def test_method_stub_should_include_self(): method = get_function("m", params=["self"], rtype="None") code = get_class("C", methods=[method]) assert get_stub(code) == "class C:\n def m(self) -> None: ...\n" def test_method_stub_should_include_params(): method = get_function("m", params=["self", "i"], ptypes=["int"], rtype="None") code = get_class("C", methods=[method]) assert get_stub(code) == "class C:\n def m(self, i: int) -> None: ...\n" def test_if_base_builtin_then_stub_should_include_base(): code = get_class("C", bases=["dict"]) assert get_stub(code) == "class C(dict): ...\n" def test_if_base_from_imported_then_stub_should_include_import(): code = "from x import A\n" code += "\n\n" + get_class("C", bases=["A"]) assert get_stub(code) == "from x import A\n\nclass C(A): ...\n" def test_if_base_imported_qualified_then_stub_should_include_import(): code = "import x\n" code += "\n\n" + get_class("C", bases=["x.A"]) assert get_stub(code) == "import x\n\nclass C(x.A): ...\n" def test_if_base_from_imported_qualified_then_stub_should_include_import(): code = "from x import y\n" code += "\n\n" + get_class("C", bases=["y.A"]) assert get_stub(code) == "from x import y\n\nclass C(y.A): ...\n" def test_if_base_unimported_qualified_then_stub_should_generate_import(): code = get_class("C", bases=["x.y.A"]) assert get_stub(code) == "import x.y\n\nclass C(x.y.A): ...\n" def test_if_base_relative_imported_qualified_then_stub_should_include_import(): code = "from . import x\n" code += "\n\n" + get_class("C", bases=["x.A"]) assert get_stub(code) == "from . import x\n\nclass C(x.A): ...\n" def test_class_sig_should_be_moved_to_init_method(): method = get_function("__init__", params=["self", "x"], rtype=None) code = get_class("C", sig="(str) -> int", methods=[method]) assert get_stub(code) == "class C:\n def __init__(self, x: str) -> int: ...\n" def test_class_sig_should_not_overwrite_existing_init_sig(): method = get_function("__init__", params=["self", "x"], ptypes=["int"], rtype="None") code = get_class("C", sig="(str) -> int", methods=[method]) assert get_stub(code) == "class C:\n def __init__(self, x: int) -> None: ...\n" def test_if_method_decorated_unknown_then_stub_should_ignore(): method = get_function("m", params=["self"], rtype="None", decorators=["@foo"]) code = get_class("C", methods=[method]) assert get_stub(code) == "class C:\n def m(self) -> None: ...\n" def test_if_method_decorated_callable_unknown_then_stub_should_ignore(): method = get_function("m", params=["self"], rtype="None", decorators=["@foo()"]) code = get_class("C", methods=[method]) assert get_stub(code) == "class C:\n def m(self) -> None: ...\n" def test_if_method_decorated_staticmethod_then_stub_should_include_decorator(): method = get_function("m", rtype="None", decorators=["@staticmethod"]) code = get_class("C", methods=[method]) assert get_stub(code) == "class C:\n @staticmethod\n def m() -> None: ...\n" def test_if_method_decorated_classmethod_then_stub_should_include_decorator(): method = get_function("m", params=["cls"], rtype="None", decorators=["@classmethod"]) code = get_class("C", methods=[method]) assert get_stub(code) == "class C:\n @classmethod\n def m(cls) -> None: ...\n" def test_if_method_decorated_property_then_stub_should_include_decorator(): method = get_function("m", params=["self"], rtype="None", decorators=["@property"]) code = get_class("C", methods=[method]) assert get_stub(code) == "class C:\n @property\n def m(self) -> None: ...\n" def test_if_method_decorated_property_setter_then_stub_should_include_decorator(): method = get_function("m", params=["self"], rtype="None", decorators=["@x.setter"]) code = get_class("C", methods=[method]) assert get_stub(code) == "class C:\n @x.setter\n def m(self) -> None: ...\n" def test_module_variable_type_comment_builtin_should_be_ellipsized(): code = "n = 42 # sig: int\n" assert get_stub(code) == "n = ... # type: int\n" def test_module_variable_type_comment_from_imported_should_include_import(): code = "from x import A\n\nn = 42 # sig: A\n" "" assert get_stub(code) == "from x import A\n\nn = ... # type: A\n" def test_module_variable_type_comment_imported_qualified_should_include_import(): code = "import x\n\nn = 42 # sig: x.A\n" "" assert get_stub(code) == "import x\n\nn = ... # type: x.A\n" def test_module_variable_type_comment_relative_qualified_should_include_import(): code = "from . import x\n\nn = 42 # sig: x.A\n" "" assert get_stub(code) == "from . import x\n\nn = ... # type: x.A\n" def test_module_variable_type_comment_unimported_qualified_should_include_import(): code = "n = 42 # sig: x.y.A\n" "" assert get_stub(code) == "import x.y\n\nn = ... # type: x.y.A\n" def test_get_stub_comment_instance_variable(): method = get_function("m", params=["self"], rtype="None", body="self.a = 42 # sig: int") code = get_class("C", methods=[method]) assert ( get_stub(code) == "class C:\n a = ... # type: int\n def m(self) -> None: ...\n" ) def test_stub_should_use_alias_comment(): code = "# sigalias: B = int\n\nn = 42 # sig: B\n" "" assert get_stub(code) == "B = int\n\nn = ... # type: B\n" def test_stub_should_exclude_function_without_sig(): code = get_function("f", rtype="None") code += "\n\n" + get_function("g", desc="") assert get_stub(code) == "def f() -> None: ...\n" def test_get_stub_typing_import_should_come_first(): code = "from x import A\n" code += "\n\n" + get_function("f", params=["a", "l"], ptypes=["A", "List"], rtype="None") assert ( get_stub(code) == "from typing import List\n\nfrom x import A\n\ndef f(a: A, l: List) -> None: ...\n" ) PK!H&,*pygenstub-1.2.3.dist-info/entry_points.txtN+I/N.,()*LO+.)Mr3PK!|wfKK%pygenstub-1.2.3.dist-info/LICENSE.txt GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . PK!H|n-WYpygenstub-1.2.3.dist-info/WHEEL A н#Z;/" bFF]xzwK;<*mTֻ0*Ri.4Vm0[H, JPK!Hm[r "pygenstub-1.2.3.dist-info/METADATAV]o6}篸KԦ 5A %"Iѿ߹%i1$hs*SA [&t$'U脪fK<uQ($tՄ-ehfrMPNh =!T>&,Lm1F& . nVe>T ~;⬆kGI7ׁnar}=ԅ2yB嗠om6NOt=vp,y73B/unB $4+g: (\Z.eԃ¹-} ޡ+d}ϧ_;Ό.S͢аuYΪ%TO!-z^u5;f?WnSA}Dc+Î83G+\r^cqnƙ"><|3į%S!zGd<)Mhh;I9[p|px€m@]8PPwm=d 2 HgYPBȃh@%X'Y5f2!ݑ"TUm7udSld#,Ƴh_3d8H?,f}p<Dka2yNSMu5!$ldӆ ;dC|YJr7"N{tY+ Ra.:D)p.Eq.(3h=5~7ٳ RtW 2Nhkw}'[-ir\3#nUB4񙐔r[ cN0v/&] ^3 ʔ2!şTt{n`UeAWp@ DvAb?a. 7h 6"dL?GX->bCtT( q떧4#L4MXFH)lE(r!PK!H!) pygenstub-1.2.3.dist-info/RECORD}ҹH> (C1 HB ˿Tmspi1@"/;u\7oRtXNkH.(F`.K3fyYgoN{EtDgUrKgL'L%؍C-#bT&dk op1]F'_2{tqU#̸/?C+ˡҝPXyr4 9˞6Ri`ܷtm緤AwB"hĬlUvgmN[<8,F8YgPqMb.G1(<+mpTVyO/(_ \v*+ar?ZG`{hfUxMӂ'ؤvhQU˭Lk^sr!qЈ&(VKB4? #pgIwI]^}e+3Q2_JfNd ӊo4ZJ|ε*,IyJW0z27Jc[ulOzX0=ǐP2 !X_k d?e;׭wC2JNmmoKcKjK ⊲o8z% elNk>TPvLhӿ{E2 PK!0s$ $ HISTORY.rstPK!)|cc M docs/MakefilePK! docs/source/_static/custom.cssPK!}dFF docs/source/api.rstPK!i docs/source/conf.pyPK!+(| docs/source/features.rstPK!L3docs/source/history.rstPK!>  3docs/source/index.rstPK!˛ll 5pygenstub.pyPK!q Ypygenstub.pyiPK![=etests/test_cli.pyPK!AA<tests/test_stub.pyPK!H&,*zpygenstub-1.2.3.dist-info/entry_points.txtPK!|wfKK%pygenstub-1.2.3.dist-info/LICENSE.txtPK!H|n-WYvpygenstub-1.2.3.dist-info/WHEELPK!Hm[r " pygenstub-1.2.3.dist-info/METADATAPK!H!) pygenstub-1.2.3.dist-info/RECORDPK#