本文整理汇总了Python中mypy.options.Options.strict_optional方法的典型用法代码示例。如果您正苦于以下问题:Python Options.strict_optional方法的具体用法?Python Options.strict_optional怎么用?Python Options.strict_optional使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mypy.options.Options
的用法示例。
在下文中一共展示了Options.strict_optional方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_case
# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import strict_optional [as 别名]
def run_case(self, testcase: DataDrivenTestCase) -> None:
try:
line = testcase.input[0]
mask = ''
if line.startswith('##'):
mask = '(' + line[2:].strip() + ')$'
src = '\n'.join(testcase.input)
options = Options()
options.strict_optional = False # TODO: Enable strict optional checking
options.use_builtins_fixtures = True
options.show_traceback = True
options.export_types = True
result = build.build(sources=[BuildSource('main', None, src)],
options=options,
alt_lib_path=test_temp_dir)
a = result.errors
map = result.types
nodes = map.keys()
# Ignore NameExpr nodes of variables with explicit (trivial) types
# to simplify output.
searcher = SkippedNodeSearcher()
for file in result.files.values():
file.accept(searcher)
ignored = searcher.nodes
# Filter nodes that should be included in the output.
keys = []
for node in nodes:
if node.line is not None and node.line != -1 and map[node]:
if ignore_node(node) or node in ignored:
continue
if (re.match(mask, short_type(node))
or (isinstance(node, NameExpr)
and re.match(mask, node.name))):
# Include node in output.
keys.append(node)
for key in sorted(keys,
key=lambda n: (n.line, short_type(n),
str(n) + str(map[n]))):
ts = str(map[key]).replace('*', '') # Remove erased tags
ts = ts.replace('__main__.', '')
a.append('{}({}) : {}'.format(short_type(key), key.line, ts))
except CompileError as e:
a = e.messages
assert_string_arrays_equal(
testcase.output, a,
'Invalid type checker output ({}, line {})'.format(testcase.file,
testcase.line))
示例2: parse_options
# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import strict_optional [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
示例3: process_options
# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import strict_optional [as 别名]
#.........这里部分代码省略.........
"Note: by default, mypy ignores any untyped function definitions "
"and assumes any calls to such functions have a return "
"type of 'Any'.")
add_invertible_flag('--disallow-untyped-calls', default=False, strict_flag=True,
help="Disallow calling functions without type annotations"
" from functions with type annotations",
group=untyped_group)
add_invertible_flag('--disallow-untyped-defs', default=False, strict_flag=True,
help="Disallow defining functions without type annotations"
" or with incomplete type annotations",
group=untyped_group)
add_invertible_flag('--disallow-incomplete-defs', default=False, strict_flag=True,
help="Disallow defining functions with incomplete type annotations",
group=untyped_group)
add_invertible_flag('--check-untyped-defs', default=False, strict_flag=True,
help="Type check the interior of functions without type annotations",
group=untyped_group)
add_invertible_flag('--disallow-untyped-decorators', default=False, strict_flag=True,
help="Disallow decorating typed functions with untyped decorators",
group=untyped_group)
none_group = parser.add_argument_group(
title='None and Optional handling',
description="Adjust how values of type 'None' are handled. For more context on "
"how mypy handles values of type 'None', see: "
"mypy.readthedocs.io/en/latest/kinds_of_types.html#no-strict-optional")
add_invertible_flag('--no-implicit-optional', default=False, strict_flag=True,
help="Don't assume arguments with default values of None are Optional",
group=none_group)
none_group.add_argument(
'--strict-optional', action='store_true',
help=argparse.SUPPRESS)
none_group.add_argument(
'--no-strict-optional', action='store_false', dest='strict_optional',
help="Disable strict Optional checks (inverse: --strict-optional)")
none_group.add_argument(
'--strict-optional-whitelist', metavar='GLOB', nargs='*',
help="Suppress strict Optional errors in all but the provided files; "
"implies --strict-optional (may suppress certain other errors "
"in non-whitelisted files)")
lint_group = parser.add_argument_group(
title='Warnings',
description="Detect code that is sound but redundant or problematic.")
add_invertible_flag('--warn-redundant-casts', default=False, strict_flag=True,
help="Warn about casting an expression to its inferred type",
group=lint_group)
add_invertible_flag('--warn-unused-ignores', default=False, strict_flag=True,
help="Warn about unneeded '# type: ignore' comments",
group=lint_group)
add_invertible_flag('--no-warn-no-return', dest='warn_no_return', default=True,
help="Do not warn about functions that end without returning",
group=lint_group)
add_invertible_flag('--warn-return-any', default=False, strict_flag=True,
help="Warn about returning values of type Any"
" from non-Any typed functions",
group=lint_group)
# Note: this group is intentionally added here even though we don't add
# --strict to this group near the end.
#
# That way, this group will appear after the various strictness groups
# but before the remaining flags.
# We add `--strict` near the end so we don't accidentally miss any strictness
# flags that are added after this group.
strictness_group = parser.add_argument_group(
示例4: process_options
# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import strict_optional [as 别名]
def process_options(args: List[str],
require_targets: bool = True
) -> Tuple[List[BuildSource], Options]:
"""Parse command line arguments."""
# Make the help output a little less jarring.
help_factory = (lambda prog:
argparse.RawDescriptionHelpFormatter(prog=prog,
max_help_position=28)) # type: Any
parser = argparse.ArgumentParser(prog='mypy', epilog=FOOTER,
fromfile_prefix_chars='@',
formatter_class=help_factory)
# Unless otherwise specified, arguments will be parsed directly onto an
# Options object. Options that require further processing should have
# their `dest` prefixed with `special-opts:`, which will cause them to be
# parsed into the separate special_opts namespace object.
parser.add_argument('-v', '--verbose', action='count', dest='verbosity',
help="more verbose messages")
parser.add_argument('-V', '--version', action='version',
version='%(prog)s ' + __version__)
parser.add_argument('--python-version', type=parse_version, metavar='x.y',
help='use Python x.y')
parser.add_argument('--platform', action='store', metavar='PLATFORM',
help="typecheck special-cased code for the given OS platform "
"(defaults to sys.platform).")
parser.add_argument('-2', '--py2', dest='python_version', action='store_const',
const=defaults.PYTHON2_VERSION, help="use Python 2 mode")
parser.add_argument('--ignore-missing-imports', action='store_true',
help="silently ignore imports of missing modules")
parser.add_argument('--follow-imports', choices=['normal', 'silent', 'skip', 'error'],
default='normal', help="how to treat imports (default normal)")
parser.add_argument('--disallow-untyped-calls', action='store_true',
help="disallow calling functions without type annotations"
" from functions with type annotations")
parser.add_argument('--disallow-untyped-defs', action='store_true',
help="disallow defining functions without type annotations"
" or with incomplete type annotations")
parser.add_argument('--check-untyped-defs', action='store_true',
help="type check the interior of functions without type annotations")
parser.add_argument('--disallow-subclassing-any', action='store_true',
help="disallow subclassing values of type 'Any' when defining classes")
parser.add_argument('--warn-incomplete-stub', action='store_true',
help="warn if missing type annotation in typeshed, only relevant with"
" --check-untyped-defs enabled")
parser.add_argument('--warn-redundant-casts', action='store_true',
help="warn about casting an expression to its inferred type")
parser.add_argument('--warn-no-return', action='store_true',
help="warn about functions that end without returning")
parser.add_argument('--warn-unused-ignores', action='store_true',
help="warn about unneeded '# type: ignore' comments")
parser.add_argument('--show-error-context', action='store_false',
dest='hide_error_context',
help='Precede errors with "note:" messages explaining context')
parser.add_argument('--fast-parser', action='store_true',
help="enable fast parser (recommended except on Windows)")
parser.add_argument('-i', '--incremental', action='store_true',
help="enable experimental module cache")
parser.add_argument('--cache-dir', action='store', metavar='DIR',
help="store module cache info in the given folder in incremental mode "
"(defaults to '{}')".format(defaults.CACHE_DIR))
parser.add_argument('--strict-optional', action='store_true',
dest='strict_optional',
help="enable experimental strict Optional checks")
parser.add_argument('--strict-optional-whitelist', metavar='GLOB', nargs='*',
help="suppress strict Optional errors in all but the provided files "
"(experimental -- read documentation before using!). "
"Implies --strict-optional. Has the undesirable side-effect of "
"suppressing other errors in non-whitelisted files.")
parser.add_argument('--junit-xml', help="write junit.xml to the given file")
parser.add_argument('--pdb', action='store_true', help="invoke pdb on fatal error")
parser.add_argument('--show-traceback', '--tb', action='store_true',
help="show traceback on fatal error")
parser.add_argument('--stats', action='store_true', dest='dump_type_stats', help="dump stats")
parser.add_argument('--inferstats', action='store_true', dest='dump_inference_stats',
help="dump type inference stats")
parser.add_argument('--custom-typing', metavar='MODULE', dest='custom_typing_module',
help="use a custom typing module")
parser.add_argument('--custom-typeshed-dir', metavar='DIR',
help="use the custom typeshed in DIR")
parser.add_argument('--scripts-are-modules', action='store_true',
help="Script x becomes module x instead of __main__")
parser.add_argument('--config-file',
help="Configuration file, must have a [mypy] section "
"(defaults to {})".format(defaults.CONFIG_FILE))
parser.add_argument('--show-column-numbers', action='store_true',
dest='show_column_numbers',
help="Show column numbers in error messages")
parser.add_argument('--find-occurrences', metavar='CLASS.MEMBER',
dest='special-opts:find_occurrences',
help="print out all usages of a class member (experimental)")
# hidden options
# --shadow-file a.py tmp.py will typecheck tmp.py in place of a.py.
# Useful for tools to make transformations to a file to get more
# information from a mypy run without having to change the file in-place
# (e.g. by adding a call to reveal_type).
parser.add_argument('--shadow-file', metavar='PATH', nargs=2, dest='shadow_file',
help=argparse.SUPPRESS)
# --debug-cache will disable any cache-related compressions/optimizations,
# which will make the cache writing process output pretty-printed JSON (which
#.........这里部分代码省略.........
示例5: process_options
# 需要导入模块: from mypy.options import Options [as 别名]
# 或者: from mypy.options.Options import strict_optional [as 别名]
#.........这里部分代码省略.........
# Parse command line for real, using a split namespace.
special_opts = argparse.Namespace()
parser.parse_args(args, SplitNamespace(options, special_opts, 'special-opts:'))
# --use-python-path is no longer supported; explain why.
if special_opts.use_python_path:
parser.error("Sorry, --use-python-path is no longer supported.\n"
"If you are trying this because your code depends on a library module,\n"
"you should really investigate how to obtain stubs for that module.\n"
"See https://github.com/python/mypy/issues/1411 for more discussion."
)
# Process deprecated options
if special_opts.disallow_any:
print("--disallow-any option was split up into multiple flags. "
"See http://mypy.readthedocs.io/en/latest/command_line.html#disallow-any-flags")
if options.strict_boolean:
print("Warning: --strict-boolean is deprecated; "
"see https://github.com/python/mypy/issues/3195", file=sys.stderr)
if special_opts.almost_silent:
print("Warning: --almost-silent has been replaced by "
"--follow-imports=errors", file=sys.stderr)
if options.follow_imports == 'normal':
options.follow_imports = 'errors'
elif special_opts.silent_imports:
print("Warning: --silent-imports has been replaced by "
"--ignore-missing-imports --follow-imports=skip", file=sys.stderr)
options.ignore_missing_imports = True
if options.follow_imports == 'normal':
options.follow_imports = 'skip'
if special_opts.dirty_stubs:
print("Warning: -f/--dirty-stubs is deprecated and no longer necessary. Mypy no longer "
"checks the git status of stubs.",
file=sys.stderr)
if special_opts.fast_parser:
print("Warning: --fast-parser is now the default (and only) parser.")
if special_opts.no_fast_parser:
print("Warning: --no-fast-parser no longer has any effect. The fast parser "
"is now mypy's default and only parser.")
# Check for invalid argument combinations.
if require_targets:
code_methods = sum(bool(c) for c in [special_opts.modules + special_opts.packages,
special_opts.command,
special_opts.files])
if code_methods == 0:
parser.error("Missing target module, package, files, or command.")
elif code_methods > 1:
parser.error("May only specify one of: module/package, files, or command.")
# Set build flags.
if options.strict_optional_whitelist is not None:
# TODO: Deprecate, then kill this flag
options.strict_optional = True
if special_opts.find_occurrences:
experiments.find_occurrences = special_opts.find_occurrences.split('.')
assert experiments.find_occurrences is not None
if len(experiments.find_occurrences) < 2:
parser.error("Can only find occurrences of class members.")
if len(experiments.find_occurrences) != 2:
parser.error("Can only find occurrences of non-nested class members.")
# Set reports.
for flag, val in vars(special_opts).items():
if flag.endswith('_report') and val is not None:
report_type = flag[:-7].replace('_', '-')
report_dir = val
options.report_dirs[report_type] = report_dir
# Let quick_and_dirty imply incremental.
if options.quick_and_dirty:
options.incremental = True
# Set target.
if special_opts.modules + special_opts.packages:
options.build_type = BuildType.MODULE
lib_path = [os.getcwd()] + build.mypy_path()
targets = []
# TODO: use the same cache as the BuildManager will
cache = build.FindModuleCache()
for p in special_opts.packages:
if os.sep in p or os.altsep and os.altsep in p:
fail("Package name '{}' cannot have a slash in it.".format(p))
p_targets = cache.find_modules_recursive(p, lib_path)
if not p_targets:
fail("Can't find package '{}'".format(p))
targets.extend(p_targets)
for m in special_opts.modules:
targets.append(BuildSource(None, m, None))
return targets, options
elif special_opts.command:
options.build_type = BuildType.PROGRAM_TEXT
targets = [BuildSource(None, None, '\n'.join(special_opts.command))]
return targets, options
else:
try:
targets = create_source_list(special_opts.files, options)
except InvalidSourceList as e:
fail(str(e))
return targets, options