How to use the monkeytype.stubs.ExistingAnnotationStrategy function in MonkeyType

To help you get started, we’ve selected a few MonkeyType examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Instagram / MonkeyType / tests / test_stubs.py View on Github external
def test_render_yield_typed_dict(self):
        function = FunctionDefinition.from_callable_and_traced_types(
            Dummy.an_instance_method,
            {
                'foo': int,
                'bar': int,
            },
            int,
            yield_type=TypedDict(DUMMY_TYPED_DICT_NAME, {'a': int, 'b': str}),
            existing_annotation_strategy=ExistingAnnotationStrategy.IGNORE
        )
        entries = [function]
        expected = '\n'.join([
            'from mypy_extensions import TypedDict',
            'from typing import Generator',
            '',
            '',
            'class DummyAnInstanceMethodYieldTypedDict(TypedDict):',
            '    a: int',
            '    b: str',
            '',
            '',
            'class Dummy:',
            '    def an_instance_method(',
            '        self,',
            '        foo: int,',
github Instagram / MonkeyType / tests / test_stubs.py View on Github external
def test_update_arg_avoid_incompatible_anno(self):
        """Can generate stub with no annotations where they already exist in the source."""
        sig = Signature.from_callable(UpdateSignatureHelper.has_annos)
        sig = update_signature_args(
            sig, {'a': int, 'b': int}, has_self=False, existing_annotation_strategy=ExistingAnnotationStrategy.OMIT)
        params = [
            Parameter('a', Parameter.POSITIONAL_OR_KEYWORD, annotation=inspect.Parameter.empty),
            Parameter('b', Parameter.POSITIONAL_OR_KEYWORD, annotation=int)
        ]
        assert sig == Signature(parameters=params, return_annotation=int)
github Instagram / MonkeyType / monkeytype / cli.py View on Github external
def apply_stub_handler(args: argparse.Namespace, stdout: IO, stderr: IO) -> None:
    args.existing_annotation_strategy = ExistingAnnotationStrategy.OMIT
    stub = get_stub(args, stdout, stderr)
    if stub is None:
        complain_about_no_traces(args, stderr)
        return
    module = args.module_path[0]
    mod = importlib.import_module(module)
    src_path = inspect.getfile(mod)
    src_dir = os.path.dirname(src_path)

    with tempfile.TemporaryDirectory(prefix='monkeytype') as pyi_dir:
        if src_path.endswith('__init__.py'):
            pyi_name = '__init__.pyi'
        else:
            pyi_name = module.split('.')[-1] + '.pyi'
        pyi_path = os.path.join(pyi_dir, pyi_name)
        with open(pyi_path, 'w+') as f:
github Instagram / MonkeyType / monkeytype / stubs.py View on Github external
def update_signature_args(
    sig: inspect.Signature,
    arg_types: Dict[str, type],
    has_self: bool,
    existing_annotation_strategy: ExistingAnnotationStrategy = ExistingAnnotationStrategy.REPLICATE,
) -> inspect.Signature:
    """Update argument annotations with the supplied types"""
    params = []
    for arg_idx, name in enumerate(sig.parameters):
        param = sig.parameters[name]
        typ = arg_types.get(name)
        typ = inspect.Parameter.empty if typ is None else typ
        is_self = (has_self and arg_idx == 0)
        annotated = param.annotation is not inspect.Parameter.empty
        if annotated and existing_annotation_strategy == ExistingAnnotationStrategy.OMIT:
            # generate no annotation for already-annotated args when generating
            # a stub to apply, avoiding the possibility of "incompatible
            # annotation" errors
            param = param.replace(annotation=inspect.Parameter.empty)
        # Don't touch existing annotations unless asked to ignore them
        if not is_self and ((existing_annotation_strategy == ExistingAnnotationStrategy.IGNORE) or not annotated):
            param = param.replace(annotation=typ)
        params.append(param)
    return sig.replace(parameters=params)
github Instagram / MonkeyType / monkeytype / cli.py View on Github external
)
    group = stub_parser.add_mutually_exclusive_group()
    group.add_argument(
        "--ignore-existing-annotations",
        action='store_const',
        dest='existing_annotation_strategy',
        default=ExistingAnnotationStrategy.REPLICATE,
        const=ExistingAnnotationStrategy.IGNORE,
        help='Ignore existing annotations and generate stubs only from traces.',
        )
    group.add_argument(
        "--omit-existing-annotations",
        action='store_const',
        dest='existing_annotation_strategy',
        default=ExistingAnnotationStrategy.REPLICATE,
        const=ExistingAnnotationStrategy.OMIT,
        help='Omit from stub any existing annotations in source. Implied by --apply.',
        )
    stub_parser.add_argument(
        "--diff",
        action='store_true',
        default=False,
        help='Compare stubs generated with and without considering existing annotations.',
        )
    stub_parser.set_defaults(handler=print_stub_handler)

    list_modules_parser = subparsers.add_parser(
        'list-modules',
        help='Listing of the unique set of module traces',
        description='Listing of the unique set of module traces')
    list_modules_parser.set_defaults(handler=list_modules_handler)
github Instagram / MonkeyType / monkeytype / stubs.py View on Github external
def update_signature_args(
    sig: inspect.Signature,
    arg_types: Dict[str, type],
    has_self: bool,
    existing_annotation_strategy: ExistingAnnotationStrategy = ExistingAnnotationStrategy.REPLICATE,
) -> inspect.Signature:
    """Update argument annotations with the supplied types"""
    params = []
    for arg_idx, name in enumerate(sig.parameters):
        param = sig.parameters[name]
        typ = arg_types.get(name)
        typ = inspect.Parameter.empty if typ is None else typ
        is_self = (has_self and arg_idx == 0)
        annotated = param.annotation is not inspect.Parameter.empty
        if annotated and existing_annotation_strategy == ExistingAnnotationStrategy.OMIT:
            # generate no annotation for already-annotated args when generating
            # a stub to apply, avoiding the possibility of "incompatible
            # annotation" errors
            param = param.replace(annotation=inspect.Parameter.empty)
        # Don't touch existing annotations unless asked to ignore them
        if not is_self and ((existing_annotation_strategy == ExistingAnnotationStrategy.IGNORE) or not annotated):
github Instagram / MonkeyType / monkeytype / stubs.py View on Github external
) -> inspect.Signature:
    """Update argument annotations with the supplied types"""
    params = []
    for arg_idx, name in enumerate(sig.parameters):
        param = sig.parameters[name]
        typ = arg_types.get(name)
        typ = inspect.Parameter.empty if typ is None else typ
        is_self = (has_self and arg_idx == 0)
        annotated = param.annotation is not inspect.Parameter.empty
        if annotated and existing_annotation_strategy == ExistingAnnotationStrategy.OMIT:
            # generate no annotation for already-annotated args when generating
            # a stub to apply, avoiding the possibility of "incompatible
            # annotation" errors
            param = param.replace(annotation=inspect.Parameter.empty)
        # Don't touch existing annotations unless asked to ignore them
        if not is_self and ((existing_annotation_strategy == ExistingAnnotationStrategy.IGNORE) or not annotated):
            param = param.replace(annotation=typ)
        params.append(param)
    return sig.replace(parameters=params)
github Instagram / MonkeyType / monkeytype / cli.py View on Github external
for methods attached to the class 'Baz' in module 'foo.bar'. See
https://www.python.org/dev/peps/pep-3155/ for a detailed description of the
qualname format.""")
    stub_parser.add_argument(
        "--sample-count",
        action='store_true',
        default=False,
        help='Print to stderr the numbers of traces stubs are based on'
        )
    group = stub_parser.add_mutually_exclusive_group()
    group.add_argument(
        "--ignore-existing-annotations",
        action='store_const',
        dest='existing_annotation_strategy',
        default=ExistingAnnotationStrategy.REPLICATE,
        const=ExistingAnnotationStrategy.IGNORE,
        help='Ignore existing annotations and generate stubs only from traces.',
        )
    group.add_argument(
        "--omit-existing-annotations",
        action='store_const',
        dest='existing_annotation_strategy',
        default=ExistingAnnotationStrategy.REPLICATE,
        const=ExistingAnnotationStrategy.OMIT,
        help='Omit from stub any existing annotations in source. Implied by --apply.',
        )
    stub_parser.add_argument(
        "--diff",
        action='store_true',
        default=False,
        help='Compare stubs generated with and without considering existing annotations.',
        )