コード例 #1
0
ファイル: log_parsers.py プロジェクト: Mu-L/airbyte
def generate_mypy_rules() -> Mapping[str, Rule]:
    try:
        addl_code = ErrorCode(
            code="unknown",
            description="Unknown error",
            category="General",
        )
    except NameError:
        return []
    return {
        f"[{err.code}]":
        Rule(rule_type=Rule.Type.code_smell,
             key=err.code,
             name=err.code.replace("-", " ").capitalize() + " (mypy)",
             description=err.description,
             tool_name="mypy",
             severity=IssueSeverity.minor,
             template="python:CommentRegularExpression")
        for err in list(mypy_error_codes.values()) + [addl_code]
    }
コード例 #2
0
            code=error_layer_input,
        )
    if l1_type.args[1] != l2_type.args[1]:
        api.fail(
            f"Layer output ({l1_type.args[1]}) not compatible with next layer output ({l2_type.args[1]})",
            l1_arg,
            code=error_layer_output,
        )
        api.fail(
            f"Layer output ({l2_type.args[1]}) not compatible with previous layer output ({l1_type.args[1]})",
            l2_arg,
            code=error_layer_output,
        )


error_layer_input = ErrorCode("layer-mismatch-input", "Invalid layer input",
                              "Thinc")
error_layer_output = ErrorCode("layer-mismatch-output", "Invalid layer output",
                               "Thinc")


class IntrospectChecker(TypeChecker):
    def __init__(
        self,
        errors: Errors,
        modules: Dict[str, MypyFile],
        options: Options,
        tree: MypyFile,
        path: str,
        plugin: Plugin,
    ):
        self._error_messages: List[str] = []
コード例 #3
0
    def set_values_dict(self) -> Dict[str, Any]:
        return {k: v for k, v in self.__dict__.items() if v is not None}

    def update(self, config: Optional["ModelConfigData"]) -> None:
        if config is None:
            return
        for k, v in config.set_values_dict().items():
            setattr(self, k, v)

    def setdefault(self, key: str, value: Any) -> None:
        if getattr(self, key) is None:
            setattr(self, key, value)


ERROR_ORM = ErrorCode("pydantic-orm", "Invalid from_orm call", "Pydantic")
ERROR_CONFIG = ErrorCode("pydantic-config", "Invalid config value", "Pydantic")
ERROR_ALIAS = ErrorCode("pydantic-alias", "Dynamic alias disallowed",
                        "Pydantic")
ERROR_UNEXPECTED = ErrorCode("pydantic-unexpected", "Unexpected behavior",
                             "Pydantic")
ERROR_UNTYPED = ErrorCode("pydantic-field", "Untyped field disallowed",
                          "Pydantic")


def error_from_orm(model_name: str, api: CheckerPluginInterface,
                   context: Context) -> None:
    api.fail(f'"{model_name}" does not have orm_mode=True',
             context,
             code=ERROR_ORM)
コード例 #4
0
    def set_values_dict(self) -> Dict[str, Any]:
        return {k: v for k, v in self.__dict__.items() if v is not None}

    def update(self, config: Optional['ModelConfigData']) -> None:
        if config is None:
            return
        for k, v in config.set_values_dict().items():
            setattr(self, k, v)

    def setdefault(self, key: str, value: Any) -> None:
        if getattr(self, key) is None:
            setattr(self, key, value)


ERROR_ORM = ErrorCode('pydantic-orm', 'Invalid from_orm call', 'Pydantic')
ERROR_CONFIG = ErrorCode('pydantic-config', 'Invalid config value', 'Pydantic')
ERROR_ALIAS = ErrorCode('pydantic-alias', 'Dynamic alias disallowed',
                        'Pydantic')
ERROR_UNEXPECTED = ErrorCode('pydantic-unexpected', 'Unexpected behavior',
                             'Pydantic')
ERROR_UNTYPED = ErrorCode('pydantic-field', 'Untyped field disallowed',
                          'Pydantic')


def error_from_orm(model_name: str, api: CheckerPluginInterface,
                   context: Context) -> None:
    api.fail(f'"{model_name}" does not have orm_mode=True',
             context,
             code=ERROR_ORM)
コード例 #5
0
# pylint: skip-file
"""JSON Class Mypy plugin for type checking JSON Class classes and objects."""
from typing import Optional, Callable, Any
from mypy.plugin import Plugin, ClassDefContext
from mypy.options import Options
from mypy.types import AnyType, TypeOfAny
from mypy.nodes import (CallExpr, LambdaExpr, MemberExpr, TempNode, TypeInfo,
                        AssignmentStmt, NameExpr, PlaceholderNode, Var)
from mypy.errorcodes import ErrorCode

JSONCLASS_DECORATOR_FULLNAME = 'jsonclasses.jsonclass.jsonclass'
JSONCLASS_TYPES_FULLNAME = 'jsonclasses.types.types'

ERROR_UNTYPED = ErrorCode('jsonclass-field', 'Untyped field disallowed', 'JSON Class')
ERROR_MULTIPLE_DEFAULT_VALUES = ErrorCode('jsonclass-field',
                                          'Multiple default values defined',
                                          'JSON Class')


def is_json_class_types_expr(expr: Any) -> bool:
    if isinstance(expr, NameExpr):
        return expr.fullname == JSONCLASS_TYPES_FULLNAME
    if isinstance(expr, MemberExpr):
        return is_json_class_types_expr(expr.expr)
    if isinstance(expr, CallExpr):
        return is_json_class_types_expr(expr.callee)
    return False


def json_class_types_default_arg_expr(expr: Any) -> Any:
    if isinstance(expr, NameExpr):
コード例 #6
0
ファイル: errorcodes.py プロジェクト: ytec-nl/django-stubs
from mypy.errorcodes import ErrorCode

MANAGER_UNTYPED = ErrorCode("django-manager", "Untyped manager disallowed",
                            "Django")
コード例 #7
0
)
from mypy.options import Options
from mypy.plugin import (
    MethodContext,
    Plugin,
)
from mypy.types import (
    get_proper_type,
    ProperType,
    Type,
)
import typing_extensions as te

ERROR_BAD_ARG: te.Final[ErrorCode] = ErrorCode(
    'logger-arg',
    'Positional argument of loguru handler is not valid for given message',
    'loguru',
)
ERROR_BAD_KWARG: te.Final[ErrorCode] = ErrorCode(
    'logger-kwarg',
    'Named argument of loguru handler is not valid for given message',
    'loguru',
)
NOTE_EDGE_CASE: te.Final[str] = (
    'Congratulations!'
    'You have found an edge case in the loguru plugin.'
    'Please open an issue :)')


class Opts(t.NamedTuple):
    lazy: bool
コード例 #8
0
from typing import Optional

from mypy.errorcodes import ErrorCode
from mypy.plugin import FunctionContext
from mypy.types import Type
from typing_extensions import Final

ERROR_UNKNOWN_PLUGIN: Final[ErrorCode] = ErrorCode(
    'axion-no-plugin',
    'Unknown axion plugin',
    'Plugin',
)
ERROR_NOT_OAS_OP: Final[ErrorCode] = ErrorCode(
    'axion-no-op',
    'Handler does not match any OAS operation',
    'OAS',
)
ERROR_INVALID_OAS_ARG: Final[ErrorCode] = ErrorCode(
    'axion-arg-type',
    'Handler argument type does not conform to OAS specification',
    'OAS',
)
ERROR_INVALID_OAS_VALUE: Final[ErrorCode] = ErrorCode(
    'axion-arg-value',
    'Handler argument (default) value does not conform to OAS specification',
    'OAS',
)


def not_oas_handler(
    msg: str,
コード例 #9
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Callable, Optional, Type as TypingType, Union

from mypy.errorcodes import ErrorCode
from mypy.nodes import FuncBase, SymbolNode
from mypy.options import Options
from mypy.plugin import AnalyzeTypeContext, Plugin
from mypy.semanal import set_callable_name  # type: ignore
from mypy.types import Type, TypeVar

T = TypeVar("T")

VALIDATOR_TYPE = "strongtyping.strong_typing_utils.Validator"  # type: Final
ERROR_UNEXPECTED = ErrorCode("strongtyping-unexpected", "Unexpected behavior",
                             "strongtyping")


def plugin(version: str) -> "TypingType[Plugin]":
    """
    `version` is the mypy version string
    We might want to use this to print a warning if the mypy version being used is
    newer, or especially older, than we expect (or need).
    """
    return StrongtypingPlugin


class StrongtypingPlugin(Plugin):
    def __init__(self, options: Options) -> None:
        super().__init__(options)