当前位置: 首页>>代码示例>>Python>>正文


Python Options.python_version方法代码示例

本文整理汇总了Python中mypy.options.Options.python_version方法的典型用法代码示例。如果您正苦于以下问题:Python Options.python_version方法的具体用法?Python Options.python_version怎么用?Python Options.python_version使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mypy.options.Options的用法示例。


在下文中一共展示了Options.python_version方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_semanal_options

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]
def get_semanal_options() -> Options:
    options = Options()
    options.use_builtins_fixtures = True
    options.semantic_analysis_only = True
    options.show_traceback = True
    options.python_version = PYTHON3_VERSION
    return options
开发者ID:sixolet,项目名称:mypy,代码行数:9,代码来源:testsemanal.py

示例2: generate_stub

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]
def generate_stub(path: str,
                  output_dir: str,
                  _all_: Optional[List[str]] = None,
                  target: Optional[str] = None,
                  add_header: bool = False,
                  module: Optional[str] = None,
                  pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION,
                  include_private: bool = False
                  ) -> None:
    with open(path, 'rb') as f:
        data = f.read()
    source = mypy.util.decode_python_encoding(data, pyversion)
    options = MypyOptions()
    options.python_version = pyversion
    try:
        ast = mypy.parse.parse(source, fnam=path, module=module, errors=None, options=options)
    except mypy.errors.CompileError as e:
        # Syntax error!
        for m in e.messages:
            sys.stderr.write('%s\n' % m)
        sys.exit(1)

    gen = StubGenerator(_all_, pyversion=pyversion, include_private=include_private)
    ast.accept(gen)
    if not target:
        target = os.path.join(output_dir, os.path.basename(path))
    subdir = os.path.dirname(target)
    if subdir and not os.path.isdir(subdir):
        os.makedirs(subdir)
    with open(target, 'w') as file:
        if add_header:
            write_header(file, module, pyversion=pyversion)
        file.write(''.join(gen.output()))
开发者ID:chadrik,项目名称:mypy,代码行数:35,代码来源:stubgen.py

示例3: parse_options

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]
    def parse_options(self, program_text: str, testcase: DataDrivenTestCase,
                      incremental_step: int) -> Options:
        options = Options()
        flags = re.search('# flags: (.*)$', program_text, flags=re.MULTILINE)
        if incremental_step > 1:
            flags2 = re.search('# flags{}: (.*)$'.format(incremental_step), program_text,
                               flags=re.MULTILINE)
            if flags2:
                flags = flags2

        flag_list = None
        if flags:
            flag_list = flags.group(1).split()
            targets, options = process_options(flag_list, require_targets=False)
            if targets:
                raise RuntimeError('Specifying targets via the flags pragma is not supported.')
        else:
            options = Options()

        # Allow custom python version to override testcase_pyversion
        if (not flag_list or
                all(flag not in flag_list for flag in ['--python-version', '-2', '--py2'])):
            options.python_version = testcase_pyversion(testcase.file, testcase.name)

        options.use_builtins_fixtures = True
        options.show_traceback = True
        options.incremental = True

        return options
开发者ID:greatmazinger,项目名称:mypy,代码行数:31,代码来源:testdmypy.py

示例4: parse_options

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]
def parse_options(program_text: str, testcase: DataDrivenTestCase,
                  incremental_step: int) -> Options:
    """Parse comments like '# flags: --foo' in a test case."""
    options = Options()
    flags = re.search('# flags: (.*)$', program_text, flags=re.MULTILINE)
    if incremental_step > 1:
        flags2 = re.search('# flags{}: (.*)$'.format(incremental_step), program_text,
                           flags=re.MULTILINE)
        if flags2:
            flags = flags2

    flag_list = None
    if flags:
        flag_list = flags.group(1).split()
        targets, options = process_options(flag_list, require_targets=False)
        if targets:
            # TODO: support specifying targets via the flags pragma
            raise RuntimeError('Specifying targets via the flags pragma is not supported.')
    else:
        options = Options()

    # Allow custom python version to override testcase_pyversion
    if (not flag_list or
            all(flag not in flag_list for flag in ['--python-version', '-2', '--py2'])):
        options.python_version = testcase_pyversion(testcase.file, testcase.name)

    return options
开发者ID:sixolet,项目名称:mypy,代码行数:29,代码来源:helpers.py

示例5: mypy_options

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]
def mypy_options(stubgen_options: Options) -> MypyOptions:
    """Generate mypy options using the flag passed by user."""
    options = MypyOptions()
    options.follow_imports = 'skip'
    options.incremental = False
    options.ignore_errors = True
    options.semantic_analysis_only = True
    options.python_version = stubgen_options.pyversion
    return options
开发者ID:python,项目名称:mypy,代码行数:11,代码来源:stubgen.py

示例6: test_executable_inference

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]
    def test_executable_inference(self) -> None:
        """Test the --python-executable flag with --python-version"""
        sys_ver_str = '{ver.major}.{ver.minor}'.format(ver=sys.version_info)

        base = ['file.py']  # dummy file

        # test inference given one (infer the other)
        matching_version = base + ['--python-version={}'.format(sys_ver_str)]
        _, options = process_options(matching_version)
        assert options.python_version == sys.version_info[:2]
        assert options.python_executable == sys.executable

        matching_version = base + ['--python-executable={}'.format(sys.executable)]
        _, options = process_options(matching_version)
        assert options.python_version == sys.version_info[:2]
        assert options.python_executable == sys.executable

        # test inference given both
        matching_version = base + ['--python-version={}'.format(sys_ver_str),
                                   '--python-executable={}'.format(sys.executable)]
        _, options = process_options(matching_version)
        assert options.python_version == sys.version_info[:2]
        assert options.python_executable == sys.executable

        # test that --no-site-packages will disable executable inference
        matching_version = base + ['--python-version={}'.format(sys_ver_str),
                                   '--no-site-packages']
        _, options = process_options(matching_version)
        assert options.python_version == sys.version_info[:2]
        assert options.python_executable is None

        # Test setting python_version/executable from config file
        special_opts = argparse.Namespace()
        special_opts.python_executable = None
        special_opts.python_version = None
        special_opts.no_executable = None

        # first test inferring executable from version
        options = Options()
        options.python_executable = None
        options.python_version = sys.version_info[:2]
        infer_python_executable(options, special_opts)
        assert options.python_version == sys.version_info[:2]
        assert options.python_executable == sys.executable

        # then test inferring version from executable
        options = Options()
        options.python_executable = sys.executable
        infer_python_executable(options, special_opts)
        assert options.python_version == sys.version_info[:2]
        assert options.python_executable == sys.executable
开发者ID:Michael0x2a,项目名称:mypy,代码行数:53,代码来源:testargs.py

示例7: build

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]
 def build(self, source: str,
           options: Options) -> Tuple[List[str], Optional[Dict[str, MypyFile]]]:
     options.use_builtins_fixtures = True
     options.show_traceback = True
     options.cache_dir = os.devnull
     options.python_version = PYTHON3_VERSION
     try:
         result = build.build(sources=[BuildSource('main', None, source)],
                              options=options,
                              alt_lib_path=test_temp_dir)
     except CompileError as e:
         # TODO: Is it okay to return None?
         return e.messages, None
     return result.errors, result.files
开发者ID:Michael0x2a,项目名称:mypy,代码行数:16,代码来源:testdiff.py

示例8: test_parser

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]
def test_parser(testcase):
    """Perform a single parser test case.

    The argument contains the description of the test case.
    """
    options = Options()

    if testcase.file.endswith('python2.test'):
        options.python_version = defaults.PYTHON2_VERSION
    else:
        options.python_version = defaults.PYTHON3_VERSION

    try:
        n = parse(bytes('\n'.join(testcase.input), 'ascii'),
                  fnam='main',
                  errors=None,
                  options=options)
        a = str(n).split('\n')
    except CompileError as e:
        a = e.messages
    assert_string_arrays_equal(testcase.output, a,
                               'Invalid parser output ({}, line {})'.format(
                                   testcase.file, testcase.line))
开发者ID:AXGKl,项目名称:Transcrypt,代码行数:25,代码来源:testparse.py

示例9: build

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]
 def build(self,
           source: str,
           python_version: Tuple[int, int]) -> Tuple[List[str],
                                                     Optional[Dict[str, MypyFile]],
                                                     Optional[Dict[Expression, Type]]]:
     options = Options()
     options.use_builtins_fixtures = True
     options.show_traceback = True
     options.cache_dir = os.devnull
     options.python_version = python_version
     try:
         result = build.build(sources=[BuildSource('main', None, source)],
                              options=options,
                              alt_lib_path=test_temp_dir)
     except CompileError as e:
         # TODO: Should perhaps not return None here.
         return e.messages, None, None
     return result.errors, result.files, result.types
开发者ID:sixolet,项目名称:mypy,代码行数:20,代码来源:testdeps.py

示例10: build

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]
 def build(self, source: str) -> Optional[BuildResult]:
     options = Options()
     options.incremental = True
     options.fine_grained_incremental = True
     options.use_builtins_fixtures = True
     options.show_traceback = True
     options.python_version = PYTHON3_VERSION
     main_path = os.path.join(test_temp_dir, 'main')
     with open(main_path, 'w', encoding='utf8') as f:
         f.write(source)
     try:
         result = build.build(sources=[BuildSource(main_path, None, None)],
                              options=options,
                              alt_lib_path=test_temp_dir)
     except CompileError:
         # TODO: Is it okay to return None?
         return None
     return result
开发者ID:Michael0x2a,项目名称:mypy,代码行数:20,代码来源:testmerge.py

示例11: parse_options

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]
    def parse_options(self, program_text: str, testcase: DataDrivenTestCase) -> Options:
        options = Options()
        flags = re.search("# flags: (.*)$", program_text, flags=re.MULTILINE)

        flag_list = None
        if flags:
            flag_list = flags.group(1).split()
            targets, options = process_options(flag_list, require_targets=False)
            if targets:
                # TODO: support specifying targets via the flags pragma
                raise RuntimeError("Specifying targets via the flags pragma is not supported.")
        else:
            options = Options()

        # Allow custom python version to override testcase_pyversion
        if not flag_list or all(flag not in flag_list for flag in ["--python-version", "-2", "--py2"]):
            options.python_version = testcase_pyversion(testcase.file, testcase.name)

        return options
开发者ID:JdeH,项目名称:Transcrypt,代码行数:21,代码来源:testcheck.py

示例12: build_stubs

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]
def build_stubs(mod):
    data_dir = default_data_dir(None)
    options = Options()
    options.python_version = (3, 6)
    lib_path = default_lib_path(data_dir,
                                options.python_version,
                                custom_typeshed_dir=None)
    sources = find_modules_recursive(mod, lib_path)
    try:
        res = build.build(sources=sources,
                          options=options)
        messages = res.errors
    except CompileError as error:
        messages = error.messages

    if messages:
        for msg in messages:
            print(msg)
        sys.exit(1)
    return res.files
开发者ID:Michael0x2a,项目名称:mypy,代码行数:22,代码来源:stubtest.py

示例13: test_transform

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]
def test_transform(testcase: DataDrivenTestCase) -> None:
    """Perform an identity transform test case."""

    try:
        src = '\n'.join(testcase.input)
        options = Options()
        options.use_builtins_fixtures = True
        options.semantic_analysis_only = True
        options.show_traceback = True
        options.python_version = testfile_pyversion(testcase.file)
        result = build.build(sources=[BuildSource('main', None, src)],
                             options=options,
                             alt_lib_path=test_temp_dir)
        a = result.errors
        if a:
            raise CompileError(a)
        # Include string representations of the source files in the actual
        # output.
        for fnam in sorted(result.files.keys()):
            f = result.files[fnam]

            # Omit the builtins module and files with a special marker in the
            # path.
            # TODO the test is not reliable
            if (not f.path.endswith((os.sep + 'builtins.pyi',
                                     'typing.pyi',
                                     'abc.pyi'))
                    and not os.path.basename(f.path).startswith('_')
                    and not os.path.splitext(
                        os.path.basename(f.path))[0].endswith('_')):
                t = TypeAssertTransformVisitor()
                f = t.mypyfile(f)
                a += str(f).split('\n')
    except CompileError as e:
        a = e.messages
    if testcase.normalize_output:
        a = normalize_error_messages(a)
    assert_string_arrays_equal(
        testcase.output, a,
        'Invalid semantic analyzer output ({}, line {})'.format(testcase.file,
                                                                testcase.line))
开发者ID:chadrik,项目名称:mypy,代码行数:43,代码来源:testtransform.py

示例14: parse_options

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]
def parse_options(program_text: str, testcase: DataDrivenTestCase,
                  incremental_step: int) -> Options:
    """Parse comments like '# flags: --foo' in a test case."""
    options = Options()
    flags = re.search('# flags: (.*)$', program_text, flags=re.MULTILINE)
    if incremental_step > 1:
        flags2 = re.search('# flags{}: (.*)$'.format(incremental_step), program_text,
                           flags=re.MULTILINE)
        if flags2:
            flags = flags2

    flag_list = None
    if flags:
        flag_list = flags.group(1).split()
        flag_list.append('--no-site-packages')  # the tests shouldn't need an installed Python
        targets, options = process_options(flag_list, require_targets=False)
        if targets:
            # TODO: support specifying targets via the flags pragma
            raise RuntimeError('Specifying targets via the flags pragma is not supported.')
    else:
        options = Options()
        # TODO: Enable strict optional in test cases by default (requires *many* test case changes)
        options.strict_optional = False

    # Allow custom python version to override testcase_pyversion
    if (not flag_list or
            all(flag not in flag_list for flag in ['--python-version', '-2', '--py2'])):
        options.python_version = testcase_pyversion(testcase.file, testcase.name)

    if testcase.config.getoption('--mypy-verbose'):
        options.verbosity = testcase.config.getoption('--mypy-verbose')

    if os.getenv('NEWSEMANAL'):
        if not flag_list or '--no-new-semantic-analyzer' not in flag_list:
            options.new_semantic_analyzer = True

    return options
开发者ID:Michael0x2a,项目名称:mypy,代码行数:39,代码来源:helpers.py

示例15: process_options

# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import python_version [as 别名]

#.........这里部分代码省略.........
        description="Configure how imports are discovered and followed.")
    imports_group.add_argument(
        '--ignore-missing-imports', action='store_true',
        help="Silently ignore imports of missing modules")
    imports_group.add_argument(
        '--follow-imports', choices=['normal', 'silent', 'skip', 'error'],
        default='normal', help="How to treat imports (default normal)")
    imports_group.add_argument(
        '--python-executable', action='store', metavar='EXECUTABLE',
        help="Python executable used for finding PEP 561 compliant installed"
             " packages and stubs",
        dest='special-opts:python_executable')
    imports_group.add_argument(
        '--no-site-packages', action='store_true',
        dest='special-opts:no_executable',
        help="Do not search for installed PEP 561 compliant packages")
    imports_group.add_argument(
        '--no-silence-site-packages', action='store_true',
        help="Do not silence errors in PEP 561 compliant installed packages")
    add_invertible_flag(
        '--namespace-packages', default=False,
        help="Support namespace packages (PEP 420, __init__.py-less)",
        group=imports_group)

    platform_group = parser.add_argument_group(
        title='Platform configuration',
        description="Type check code assuming it will be run under certain "
                    "runtime conditions. By default, mypy assumes your code "
                    "will be run using the same operating system and Python "
                    "version you are using to run mypy itself.")
    platform_group.add_argument(
        '--python-version', type=parse_version, metavar='x.y',
        help='Type check code assuming it will be running on Python x.y',
        dest='special-opts:python_version')
    platform_group.add_argument(
        '-2', '--py2', dest='special-opts:python_version', action='store_const',
        const=defaults.PYTHON2_VERSION,
        help="Use Python 2 mode (same as --python-version 2.7)")
    platform_group.add_argument(
        '--platform', action='store', metavar='PLATFORM',
        help="Type check special-cased code for the given OS platform "
             "(defaults to sys.platform)")
    platform_group.add_argument(
        '--always-true', metavar='NAME', action='append', default=[],
        help="Additional variable to be considered True (may be repeated)")
    platform_group.add_argument(
        '--always-false', metavar='NAME', action='append', default=[],
        help="Additional variable to be considered False (may be repeated)")

    disallow_any_group = parser.add_argument_group(
        title='Dynamic typing',
        description="Disallow the use of the dynamic 'Any' type under certain conditions.")
    disallow_any_group.add_argument(
        '--disallow-any-unimported', default=False, action='store_true',
        help="Disallow Any types resulting from unfollowed imports")
    add_invertible_flag('--disallow-subclassing-any', default=False, strict_flag=True,
                        help="Disallow subclassing values of type 'Any' when defining classes",
                        group=disallow_any_group)
    disallow_any_group.add_argument(
        '--disallow-any-expr', default=False, action='store_true',
        help='Disallow all expressions that have type Any')
    disallow_any_group.add_argument(
        '--disallow-any-decorated', default=False, action='store_true',
        help='Disallow functions that have Any in their signature '
             'after decorator transformation')
    disallow_any_group.add_argument(
开发者ID:python,项目名称:mypy,代码行数:70,代码来源:main.py


注:本文中的mypy.options.Options.python_version方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。