fname stringlengths 63 176 | rel_fname stringclasses 706
values | line int64 -1 4.5k | name stringlengths 1 81 | kind stringclasses 2
values | category stringclasses 2
values | info stringlengths 0 77.9k ⌀ |
|---|---|---|---|---|---|---|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 360 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 363 | pytype | ref | function | args=(arg_type.pytype(), format_type),
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 367 | add_message | ref | function | self.add_message("format-needs-mapping", node=node, args=type_name)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 379 | safe_infer | ref | function | rhs_tuple = utils.safe_infer(args)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 394 | add_message | ref | function | self.add_message("too-many-format-args", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 396 | add_message | ref | function | self.add_message("too-few-format-args", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 400 | safe_infer | ref | function | arg_type = utils.safe_infer(arg)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 404 | arg_matches_format_type | ref | function | and not arg_matches_format_type(arg_type, format_type)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 406 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 409 | pytype | ref | function | args=(arg_type.pytype(), format_type),
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 412 | check_messages | ref | function | @check_messages("f-string-without-interpolation")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 413 | visit_joinedstr | def | function | def visit_joinedstr(self, node: nodes.JoinedStr) -> None:
self._check_interpolation(node)
def _check_interpolation(self, node: nodes.JoinedStr) -> None:
if isinstance(node.parent, nodes.FormattedValue):
return
for value in node.values:
if isinstance(value, nodes.FormattedValue):
return
self.add_message("f-string-without-interpolation", node=node)
@check_messages(*MSGS)
def visit_call(self, node: nodes.Call) -> None:
func = utils.safe_infer(node.func)
if (
isinstance(func, astroid.BoundMethod)
and isinstance(func.bound, astroid.Instance)
and func.bound.name in {"str", "unicode", "bytes"}
):
if func.name in {"strip", "lstrip", "rstrip"} and node.args:
arg = utils.safe_infer(node.args[0])
if not isinstance(arg, nodes.Const) or not isinstance(arg.value, str):
return
if len(arg.value) != len(set(arg.value)):
self.add_message(
"bad-str-strip-call",
node=node,
args=(func.bound.name, func.name),
)
elif func.name == "format":
self._check_new_format(node, func)
def _detect_vacuous_formatting(self, node, positional_arguments):
counter = collections.Counter(
arg.name for arg in positional_arguments if isinstance(arg, nodes.Name)
)
for name, count in counter.items():
if count == 1:
continue
self.add_message(
"duplicate-string-formatting-argument", node=node, args=(name,)
)
def _check_new_format(self, node, func):
"""Check the new string formatting."""
# Skip format nodes which don't have an explicit string on the
# left side of the format operation.
# We do this because our inference engine can't properly handle
# redefinitions of the original string.
# Note that there may not be any left side at all, if the format method
# has been assigned to another variable. See issue 351. For example:
#
# fmt = 'some string {}'.format
# fmt('arg')
if isinstance(node.func, nodes.Attribute) and not isinstance(
node.func.expr, nodes.Const
):
return
if node.starargs or node.kwargs:
return
try:
strnode = next(func.bound.infer())
except astroid.InferenceError:
return
if not (isinstance(strnode, nodes.Const) and isinstance(strnode.value, str)):
return
try:
call_site = astroid.arguments.CallSite.from_call(node)
except astroid.InferenceError:
return
try:
fields, num_args, manual_pos = utils.parse_format_method_string(
strnode.value
)
except utils.IncompleteFormatString:
self.add_message("bad-format-string", node=node)
return
positional_arguments = call_site.positional_arguments
named_arguments = call_site.keyword_arguments
named_fields = {field[0] for field in fields if isinstance(field[0], str)}
if num_args and manual_pos:
self.add_message("format-combined-specification", node=node)
return
check_args = _False
# Consider "{[0]} {[1]}" as num_args.
num_args += sum(1 for field in named_fields if field == "")
if named_fields:
for field in named_fields:
if field and field not in named_arguments:
self.add_message(
"missing-format-argument-key", node=node, args=(field,)
)
for field in named_arguments:
if field not in named_fields:
self.add_message(
"unused-format-string-argument", node=node, args=(field,)
)
# num_args can be 0 if manual_pos is not.
num_args = num_args or manual_pos
if positional_arguments or num_args:
empty = any(field == "" for field in named_fields)
if named_arguments or empty:
# Verify the required number of positional arguments
# only if the .format got at least one keyword argument.
# This means that the format strings accepts both
# positional and named fields and we should warn
# when one of them is missing or is extra.
check_args = _True
else:
check_args = _True
if check_args:
# num_args can be 0 if manual_pos is not.
num_args = num_args or manual_pos
if not num_args:
self.add_message("format-string-without-interpolation", node=node)
return
if len(positional_arguments) > num_args:
self.add_message("too-many-format-args", node=node)
elif len(positional_arguments) < num_args:
self.add_message("too-few-format-args", node=node)
self._detect_vacuous_formatting(node, positional_arguments)
self._check_new_format_specifiers(node, fields, named_arguments)
def _check_new_format_specifiers(self, node, fields, named):
"""Check attribute and index access in the format
string ("{0.a}" and "{0[a]}").
"""
for key, specifiers in fields:
# Obtain the argument. If it can't be obtained
# or inferred, skip this check.
if key == "":
# {[0]} will have an unnamed argument, defaulting
# to 0. It will not be present in `named`, so use the value
# 0 for it.
key = 0
if isinstance(key, numbers.Number):
try:
argname = utils.get_argument_from_call(node, key)
except utils.NoSuchArgumentError:
continue
else:
if key not in named:
continue
argname = named[key]
if argname in (astroid.Uninferable, None):
continue
try:
argument = utils.safe_infer(argname)
except astroid.InferenceError:
continue
if not specifiers or not argument:
# No need to check this key if it doesn't
# use attribute / item access
continue
if argument.parent and isinstance(argument.parent, nodes.Arguments):
# Ignore any object coming from an argument,
# because we can't infer its value properly.
continue
previous = argument
parsed = []
for is_attribute, specifier in specifiers:
if previous is astroid.Uninferable:
break
parsed.append((is_attribute, specifier))
if is_attribute:
try:
previous = previous.getattr(specifier)[0]
except astroid.NotFoundError:
if (
hasattr(previous, "has_dynamic_getattr")
and previous.has_dynamic_getattr()
):
# Don't warn if the object has a custom __getattr__
break
path = get_access_path(key, parsed)
self.add_message(
"missing-format-attribute",
args=(specifier, path),
node=node,
)
break
else:
warn_error = _False
if hasattr(previous, "getitem"):
try:
previous = previous.getitem(nodes.Const(specifier))
except (
astroid.AstroidIndexError,
astroid.AstroidTypeError,
astroid.AttributeInferenceError,
):
warn_error = _True
except astroid.InferenceError:
break
if previous is astroid.Uninferable:
break
else:
try:
# Lookup __getitem__ in the current node,
# but skip further checks, because we can't
# retrieve the looked object
previous.getattr("__getitem__")
break
except astroid.NotFoundError:
warn_error = _True
if warn_error:
path = get_access_path(key, parsed)
self.add_message(
"invalid-format-index", args=(specifier, path), node=node
)
break
try:
previous = next(previous.infer())
except astroid.InferenceError:
# can't check further if we can't infer it
break
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 414 | _check_interpolation | ref | function | self._check_interpolation(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 416 | _check_interpolation | def | function | def _check_interpolation(self, node: nodes.JoinedStr) -> None:
if isinstance(node.parent, nodes.FormattedValue):
return
for value in node.values:
if isinstance(value, nodes.FormattedValue):
return
self.add_message("f-string-without-interpolation", node=node)
@check_messages(*MSGS)
def visit_call(self, node: nodes.Call) -> None:
func = utils.safe_infer(node.func)
if (
isinstance(func, astroid.BoundMethod)
and isinstance(func.bound, astroid.Instance)
and func.bound.name in {"str", "unicode", "bytes"}
):
if func.name in {"strip", "lstrip", "rstrip"} and node.args:
arg = utils.safe_infer(node.args[0])
if not isinstance(arg, nodes.Const) or not isinstance(arg.value, str):
return
if len(arg.value) != len(set(arg.value)):
self.add_message(
"bad-str-strip-call",
node=node,
args=(func.bound.name, func.name),
)
elif func.name == "format":
self._check_new_format(node, func)
def _detect_vacuous_formatting(self, node, positional_arguments):
counter = collections.Counter(
arg.name for arg in positional_arguments if isinstance(arg, nodes.Name)
)
for name, count in counter.items():
if count == 1:
continue
self.add_message(
"duplicate-string-formatting-argument", node=node, args=(name,)
)
def _check_new_format(self, node, func):
"""Check the new string formatting."""
# Skip format nodes which don't have an explicit string on the
# left side of the format operation.
# We do this because our inference engine can't properly handle
# redefinitions of the original string.
# Note that there may not be any left side at all, if the format method
# has been assigned to another variable. See issue 351. For example:
#
# fmt = 'some string {}'.format
# fmt('arg')
if isinstance(node.func, nodes.Attribute) and not isinstance(
node.func.expr, nodes.Const
):
return
if node.starargs or node.kwargs:
return
try:
strnode = next(func.bound.infer())
except astroid.InferenceError:
return
if not (isinstance(strnode, nodes.Const) and isinstance(strnode.value, str)):
return
try:
call_site = astroid.arguments.CallSite.from_call(node)
except astroid.InferenceError:
return
try:
fields, num_args, manual_pos = utils.parse_format_method_string(
strnode.value
)
except utils.IncompleteFormatString:
self.add_message("bad-format-string", node=node)
return
positional_arguments = call_site.positional_arguments
named_arguments = call_site.keyword_arguments
named_fields = {field[0] for field in fields if isinstance(field[0], str)}
if num_args and manual_pos:
self.add_message("format-combined-specification", node=node)
return
check_args = _False
# Consider "{[0]} {[1]}" as num_args.
num_args += sum(1 for field in named_fields if field == "")
if named_fields:
for field in named_fields:
if field and field not in named_arguments:
self.add_message(
"missing-format-argument-key", node=node, args=(field,)
)
for field in named_arguments:
if field not in named_fields:
self.add_message(
"unused-format-string-argument", node=node, args=(field,)
)
# num_args can be 0 if manual_pos is not.
num_args = num_args or manual_pos
if positional_arguments or num_args:
empty = any(field == "" for field in named_fields)
if named_arguments or empty:
# Verify the required number of positional arguments
# only if the .format got at least one keyword argument.
# This means that the format strings accepts both
# positional and named fields and we should warn
# when one of them is missing or is extra.
check_args = _True
else:
check_args = _True
if check_args:
# num_args can be 0 if manual_pos is not.
num_args = num_args or manual_pos
if not num_args:
self.add_message("format-string-without-interpolation", node=node)
return
if len(positional_arguments) > num_args:
self.add_message("too-many-format-args", node=node)
elif len(positional_arguments) < num_args:
self.add_message("too-few-format-args", node=node)
self._detect_vacuous_formatting(node, positional_arguments)
self._check_new_format_specifiers(node, fields, named_arguments)
def _check_new_format_specifiers(self, node, fields, named):
"""Check attribute and index access in the format
string ("{0.a}" and "{0[a]}").
"""
for key, specifiers in fields:
# Obtain the argument. If it can't be obtained
# or inferred, skip this check.
if key == "":
# {[0]} will have an unnamed argument, defaulting
# to 0. It will not be present in `named`, so use the value
# 0 for it.
key = 0
if isinstance(key, numbers.Number):
try:
argname = utils.get_argument_from_call(node, key)
except utils.NoSuchArgumentError:
continue
else:
if key not in named:
continue
argname = named[key]
if argname in (astroid.Uninferable, None):
continue
try:
argument = utils.safe_infer(argname)
except astroid.InferenceError:
continue
if not specifiers or not argument:
# No need to check this key if it doesn't
# use attribute / item access
continue
if argument.parent and isinstance(argument.parent, nodes.Arguments):
# Ignore any object coming from an argument,
# because we can't infer its value properly.
continue
previous = argument
parsed = []
for is_attribute, specifier in specifiers:
if previous is astroid.Uninferable:
break
parsed.append((is_attribute, specifier))
if is_attribute:
try:
previous = previous.getattr(specifier)[0]
except astroid.NotFoundError:
if (
hasattr(previous, "has_dynamic_getattr")
and previous.has_dynamic_getattr()
):
# Don't warn if the object has a custom __getattr__
break
path = get_access_path(key, parsed)
self.add_message(
"missing-format-attribute",
args=(specifier, path),
node=node,
)
break
else:
warn_error = _False
if hasattr(previous, "getitem"):
try:
previous = previous.getitem(nodes.Const(specifier))
except (
astroid.AstroidIndexError,
astroid.AstroidTypeError,
astroid.AttributeInferenceError,
):
warn_error = _True
except astroid.InferenceError:
break
if previous is astroid.Uninferable:
break
else:
try:
# Lookup __getitem__ in the current node,
# but skip further checks, because we can't
# retrieve the looked object
previous.getattr("__getitem__")
break
except astroid.NotFoundError:
warn_error = _True
if warn_error:
path = get_access_path(key, parsed)
self.add_message(
"invalid-format-index", args=(specifier, path), node=node
)
break
try:
previous = next(previous.infer())
except astroid.InferenceError:
# can't check further if we can't infer it
break
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 422 | add_message | ref | function | self.add_message("f-string-without-interpolation", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 424 | check_messages | ref | function | @check_messages(*MSGS)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 425 | visit_call | def | function | def visit_call(self, node: nodes.Call) -> None:
func = utils.safe_infer(node.func)
if (
isinstance(func, astroid.BoundMethod)
and isinstance(func.bound, astroid.Instance)
and func.bound.name in {"str", "unicode", "bytes"}
):
if func.name in {"strip", "lstrip", "rstrip"} and node.args:
arg = utils.safe_infer(node.args[0])
if not isinstance(arg, nodes.Const) or not isinstance(arg.value, str):
return
if len(arg.value) != len(set(arg.value)):
self.add_message(
"bad-str-strip-call",
node=node,
args=(func.bound.name, func.name),
)
elif func.name == "format":
self._check_new_format(node, func)
def _detect_vacuous_formatting(self, node, positional_arguments):
counter = collections.Counter(
arg.name for arg in positional_arguments if isinstance(arg, nodes.Name)
)
for name, count in counter.items():
if count == 1:
continue
self.add_message(
"duplicate-string-formatting-argument", node=node, args=(name,)
)
def _check_new_format(self, node, func):
"""Check the new string formatting."""
# Skip format nodes which don't have an explicit string on the
# left side of the format operation.
# We do this because our inference engine can't properly handle
# redefinitions of the original string.
# Note that there may not be any left side at all, if the format method
# has been assigned to another variable. See issue 351. For example:
#
# fmt = 'some string {}'.format
# fmt('arg')
if isinstance(node.func, nodes.Attribute) and not isinstance(
node.func.expr, nodes.Const
):
return
if node.starargs or node.kwargs:
return
try:
strnode = next(func.bound.infer())
except astroid.InferenceError:
return
if not (isinstance(strnode, nodes.Const) and isinstance(strnode.value, str)):
return
try:
call_site = astroid.arguments.CallSite.from_call(node)
except astroid.InferenceError:
return
try:
fields, num_args, manual_pos = utils.parse_format_method_string(
strnode.value
)
except utils.IncompleteFormatString:
self.add_message("bad-format-string", node=node)
return
positional_arguments = call_site.positional_arguments
named_arguments = call_site.keyword_arguments
named_fields = {field[0] for field in fields if isinstance(field[0], str)}
if num_args and manual_pos:
self.add_message("format-combined-specification", node=node)
return
check_args = _False
# Consider "{[0]} {[1]}" as num_args.
num_args += sum(1 for field in named_fields if field == "")
if named_fields:
for field in named_fields:
if field and field not in named_arguments:
self.add_message(
"missing-format-argument-key", node=node, args=(field,)
)
for field in named_arguments:
if field not in named_fields:
self.add_message(
"unused-format-string-argument", node=node, args=(field,)
)
# num_args can be 0 if manual_pos is not.
num_args = num_args or manual_pos
if positional_arguments or num_args:
empty = any(field == "" for field in named_fields)
if named_arguments or empty:
# Verify the required number of positional arguments
# only if the .format got at least one keyword argument.
# This means that the format strings accepts both
# positional and named fields and we should warn
# when one of them is missing or is extra.
check_args = _True
else:
check_args = _True
if check_args:
# num_args can be 0 if manual_pos is not.
num_args = num_args or manual_pos
if not num_args:
self.add_message("format-string-without-interpolation", node=node)
return
if len(positional_arguments) > num_args:
self.add_message("too-many-format-args", node=node)
elif len(positional_arguments) < num_args:
self.add_message("too-few-format-args", node=node)
self._detect_vacuous_formatting(node, positional_arguments)
self._check_new_format_specifiers(node, fields, named_arguments)
def _check_new_format_specifiers(self, node, fields, named):
"""Check attribute and index access in the format
string ("{0.a}" and "{0[a]}").
"""
for key, specifiers in fields:
# Obtain the argument. If it can't be obtained
# or inferred, skip this check.
if key == "":
# {[0]} will have an unnamed argument, defaulting
# to 0. It will not be present in `named`, so use the value
# 0 for it.
key = 0
if isinstance(key, numbers.Number):
try:
argname = utils.get_argument_from_call(node, key)
except utils.NoSuchArgumentError:
continue
else:
if key not in named:
continue
argname = named[key]
if argname in (astroid.Uninferable, None):
continue
try:
argument = utils.safe_infer(argname)
except astroid.InferenceError:
continue
if not specifiers or not argument:
# No need to check this key if it doesn't
# use attribute / item access
continue
if argument.parent and isinstance(argument.parent, nodes.Arguments):
# Ignore any object coming from an argument,
# because we can't infer its value properly.
continue
previous = argument
parsed = []
for is_attribute, specifier in specifiers:
if previous is astroid.Uninferable:
break
parsed.append((is_attribute, specifier))
if is_attribute:
try:
previous = previous.getattr(specifier)[0]
except astroid.NotFoundError:
if (
hasattr(previous, "has_dynamic_getattr")
and previous.has_dynamic_getattr()
):
# Don't warn if the object has a custom __getattr__
break
path = get_access_path(key, parsed)
self.add_message(
"missing-format-attribute",
args=(specifier, path),
node=node,
)
break
else:
warn_error = _False
if hasattr(previous, "getitem"):
try:
previous = previous.getitem(nodes.Const(specifier))
except (
astroid.AstroidIndexError,
astroid.AstroidTypeError,
astroid.AttributeInferenceError,
):
warn_error = _True
except astroid.InferenceError:
break
if previous is astroid.Uninferable:
break
else:
try:
# Lookup __getitem__ in the current node,
# but skip further checks, because we can't
# retrieve the looked object
previous.getattr("__getitem__")
break
except astroid.NotFoundError:
warn_error = _True
if warn_error:
path = get_access_path(key, parsed)
self.add_message(
"invalid-format-index", args=(specifier, path), node=node
)
break
try:
previous = next(previous.infer())
except astroid.InferenceError:
# can't check further if we can't infer it
break
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 426 | safe_infer | ref | function | func = utils.safe_infer(node.func)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 433 | safe_infer | ref | function | arg = utils.safe_infer(node.args[0])
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 437 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 443 | _check_new_format | ref | function | self._check_new_format(node, func)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 445 | _detect_vacuous_formatting | def | function | def _detect_vacuous_formatting(self, node, positional_arguments):
counter = collections.Counter(
arg.name for arg in positional_arguments if isinstance(arg, nodes.Name)
)
for name, count in counter.items():
if count == 1:
continue
self.add_message(
"duplicate-string-formatting-argument", node=node, args=(name,)
)
def _check_new_format(self, node, func):
"""Check the new string formatting."""
# Skip format nodes which don't have an explicit string on the
# left side of the format operation.
# We do this because our inference engine can't properly handle
# redefinitions of the original string.
# Note that there may not be any left side at all, if the format method
# has been assigned to another variable. See issue 351. For example:
#
# fmt = 'some string {}'.format
# fmt('arg')
if isinstance(node.func, nodes.Attribute) and not isinstance(
node.func.expr, nodes.Const
):
return
if node.starargs or node.kwargs:
return
try:
strnode = next(func.bound.infer())
except astroid.InferenceError:
return
if not (isinstance(strnode, nodes.Const) and isinstance(strnode.value, str)):
return
try:
call_site = astroid.arguments.CallSite.from_call(node)
except astroid.InferenceError:
return
try:
fields, num_args, manual_pos = utils.parse_format_method_string(
strnode.value
)
except utils.IncompleteFormatString:
self.add_message("bad-format-string", node=node)
return
positional_arguments = call_site.positional_arguments
named_arguments = call_site.keyword_arguments
named_fields = {field[0] for field in fields if isinstance(field[0], str)}
if num_args and manual_pos:
self.add_message("format-combined-specification", node=node)
return
check_args = _False
# Consider "{[0]} {[1]}" as num_args.
num_args += sum(1 for field in named_fields if field == "")
if named_fields:
for field in named_fields:
if field and field not in named_arguments:
self.add_message(
"missing-format-argument-key", node=node, args=(field,)
)
for field in named_arguments:
if field not in named_fields:
self.add_message(
"unused-format-string-argument", node=node, args=(field,)
)
# num_args can be 0 if manual_pos is not.
num_args = num_args or manual_pos
if positional_arguments or num_args:
empty = any(field == "" for field in named_fields)
if named_arguments or empty:
# Verify the required number of positional arguments
# only if the .format got at least one keyword argument.
# This means that the format strings accepts both
# positional and named fields and we should warn
# when one of them is missing or is extra.
check_args = _True
else:
check_args = _True
if check_args:
# num_args can be 0 if manual_pos is not.
num_args = num_args or manual_pos
if not num_args:
self.add_message("format-string-without-interpolation", node=node)
return
if len(positional_arguments) > num_args:
self.add_message("too-many-format-args", node=node)
elif len(positional_arguments) < num_args:
self.add_message("too-few-format-args", node=node)
self._detect_vacuous_formatting(node, positional_arguments)
self._check_new_format_specifiers(node, fields, named_arguments)
def _check_new_format_specifiers(self, node, fields, named):
"""Check attribute and index access in the format
string ("{0.a}" and "{0[a]}").
"""
for key, specifiers in fields:
# Obtain the argument. If it can't be obtained
# or inferred, skip this check.
if key == "":
# {[0]} will have an unnamed argument, defaulting
# to 0. It will not be present in `named`, so use the value
# 0 for it.
key = 0
if isinstance(key, numbers.Number):
try:
argname = utils.get_argument_from_call(node, key)
except utils.NoSuchArgumentError:
continue
else:
if key not in named:
continue
argname = named[key]
if argname in (astroid.Uninferable, None):
continue
try:
argument = utils.safe_infer(argname)
except astroid.InferenceError:
continue
if not specifiers or not argument:
# No need to check this key if it doesn't
# use attribute / item access
continue
if argument.parent and isinstance(argument.parent, nodes.Arguments):
# Ignore any object coming from an argument,
# because we can't infer its value properly.
continue
previous = argument
parsed = []
for is_attribute, specifier in specifiers:
if previous is astroid.Uninferable:
break
parsed.append((is_attribute, specifier))
if is_attribute:
try:
previous = previous.getattr(specifier)[0]
except astroid.NotFoundError:
if (
hasattr(previous, "has_dynamic_getattr")
and previous.has_dynamic_getattr()
):
# Don't warn if the object has a custom __getattr__
break
path = get_access_path(key, parsed)
self.add_message(
"missing-format-attribute",
args=(specifier, path),
node=node,
)
break
else:
warn_error = _False
if hasattr(previous, "getitem"):
try:
previous = previous.getitem(nodes.Const(specifier))
except (
astroid.AstroidIndexError,
astroid.AstroidTypeError,
astroid.AttributeInferenceError,
):
warn_error = _True
except astroid.InferenceError:
break
if previous is astroid.Uninferable:
break
else:
try:
# Lookup __getitem__ in the current node,
# but skip further checks, because we can't
# retrieve the looked object
previous.getattr("__getitem__")
break
except astroid.NotFoundError:
warn_error = _True
if warn_error:
path = get_access_path(key, parsed)
self.add_message(
"invalid-format-index", args=(specifier, path), node=node
)
break
try:
previous = next(previous.infer())
except astroid.InferenceError:
# can't check further if we can't infer it
break
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 452 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 456 | _check_new_format | def | function | def _check_new_format(self, node, func):
"""Check the new string formatting."""
# Skip format nodes which don't have an explicit string on the
# left side of the format operation.
# We do this because our inference engine can't properly handle
# redefinitions of the original string.
# Note that there may not be any left side at all, if the format method
# has been assigned to another variable. See issue 351. For example:
#
# fmt = 'some string {}'.format
# fmt('arg')
if isinstance(node.func, nodes.Attribute) and not isinstance(
node.func.expr, nodes.Const
):
return
if node.starargs or node.kwargs:
return
try:
strnode = next(func.bound.infer())
except astroid.InferenceError:
return
if not (isinstance(strnode, nodes.Const) and isinstance(strnode.value, str)):
return
try:
call_site = astroid.arguments.CallSite.from_call(node)
except astroid.InferenceError:
return
try:
fields, num_args, manual_pos = utils.parse_format_method_string(
strnode.value
)
except utils.IncompleteFormatString:
self.add_message("bad-format-string", node=node)
return
positional_arguments = call_site.positional_arguments
named_arguments = call_site.keyword_arguments
named_fields = {field[0] for field in fields if isinstance(field[0], str)}
if num_args and manual_pos:
self.add_message("format-combined-specification", node=node)
return
check_args = _False
# Consider "{[0]} {[1]}" as num_args.
num_args += sum(1 for field in named_fields if field == "")
if named_fields:
for field in named_fields:
if field and field not in named_arguments:
self.add_message(
"missing-format-argument-key", node=node, args=(field,)
)
for field in named_arguments:
if field not in named_fields:
self.add_message(
"unused-format-string-argument", node=node, args=(field,)
)
# num_args can be 0 if manual_pos is not.
num_args = num_args or manual_pos
if positional_arguments or num_args:
empty = any(field == "" for field in named_fields)
if named_arguments or empty:
# Verify the required number of positional arguments
# only if the .format got at least one keyword argument.
# This means that the format strings accepts both
# positional and named fields and we should warn
# when one of them is missing or is extra.
check_args = _True
else:
check_args = _True
if check_args:
# num_args can be 0 if manual_pos is not.
num_args = num_args or manual_pos
if not num_args:
self.add_message("format-string-without-interpolation", node=node)
return
if len(positional_arguments) > num_args:
self.add_message("too-many-format-args", node=node)
elif len(positional_arguments) < num_args:
self.add_message("too-few-format-args", node=node)
self._detect_vacuous_formatting(node, positional_arguments)
self._check_new_format_specifiers(node, fields, named_arguments)
def _check_new_format_specifiers(self, node, fields, named):
"""Check attribute and index access in the format
string ("{0.a}" and "{0[a]}").
"""
for key, specifiers in fields:
# Obtain the argument. If it can't be obtained
# or inferred, skip this check.
if key == "":
# {[0]} will have an unnamed argument, defaulting
# to 0. It will not be present in `named`, so use the value
# 0 for it.
key = 0
if isinstance(key, numbers.Number):
try:
argname = utils.get_argument_from_call(node, key)
except utils.NoSuchArgumentError:
continue
else:
if key not in named:
continue
argname = named[key]
if argname in (astroid.Uninferable, None):
continue
try:
argument = utils.safe_infer(argname)
except astroid.InferenceError:
continue
if not specifiers or not argument:
# No need to check this key if it doesn't
# use attribute / item access
continue
if argument.parent and isinstance(argument.parent, nodes.Arguments):
# Ignore any object coming from an argument,
# because we can't infer its value properly.
continue
previous = argument
parsed = []
for is_attribute, specifier in specifiers:
if previous is astroid.Uninferable:
break
parsed.append((is_attribute, specifier))
if is_attribute:
try:
previous = previous.getattr(specifier)[0]
except astroid.NotFoundError:
if (
hasattr(previous, "has_dynamic_getattr")
and previous.has_dynamic_getattr()
):
# Don't warn if the object has a custom __getattr__
break
path = get_access_path(key, parsed)
self.add_message(
"missing-format-attribute",
args=(specifier, path),
node=node,
)
break
else:
warn_error = _False
if hasattr(previous, "getitem"):
try:
previous = previous.getitem(nodes.Const(specifier))
except (
astroid.AstroidIndexError,
astroid.AstroidTypeError,
astroid.AttributeInferenceError,
):
warn_error = _True
except astroid.InferenceError:
break
if previous is astroid.Uninferable:
break
else:
try:
# Lookup __getitem__ in the current node,
# but skip further checks, because we can't
# retrieve the looked object
previous.getattr("__getitem__")
break
except astroid.NotFoundError:
warn_error = _True
if warn_error:
path = get_access_path(key, parsed)
self.add_message(
"invalid-format-index", args=(specifier, path), node=node
)
break
try:
previous = next(previous.infer())
except astroid.InferenceError:
# can't check further if we can't infer it
break
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 474 | infer | ref | function | strnode = next(func.bound.infer())
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 480 | from_call | ref | function | call_site = astroid.arguments.CallSite.from_call(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 485 | parse_format_method_string | ref | function | fields, num_args, manual_pos = utils.parse_format_method_string(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 489 | add_message | ref | function | self.add_message("bad-format-string", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 496 | add_message | ref | function | self.add_message("format-combined-specification", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 505 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 510 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 530 | add_message | ref | function | self.add_message("format-string-without-interpolation", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 533 | add_message | ref | function | self.add_message("too-many-format-args", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 535 | add_message | ref | function | self.add_message("too-few-format-args", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 537 | _detect_vacuous_formatting | ref | function | self._detect_vacuous_formatting(node, positional_arguments)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 538 | _check_new_format_specifiers | ref | function | self._check_new_format_specifiers(node, fields, named_arguments)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 540 | _check_new_format_specifiers | def | function | def _check_new_format_specifiers(self, node, fields, named):
"""Check attribute and index access in the format
string ("{0.a}" and "{0[a]}").
"""
for key, specifiers in fields:
# Obtain the argument. If it can't be obtained
# or inferred, skip this check.
if key == "":
# {[0]} will have an unnamed argument, defaulting
# to 0. It will not be present in `named`, so use the value
# 0 for it.
key = 0
if isinstance(key, numbers.Number):
try:
argname = utils.get_argument_from_call(node, key)
except utils.NoSuchArgumentError:
continue
else:
if key not in named:
continue
argname = named[key]
if argname in (astroid.Uninferable, None):
continue
try:
argument = utils.safe_infer(argname)
except astroid.InferenceError:
continue
if not specifiers or not argument:
# No need to check this key if it doesn't
# use attribute / item access
continue
if argument.parent and isinstance(argument.parent, nodes.Arguments):
# Ignore any object coming from an argument,
# because we can't infer its value properly.
continue
previous = argument
parsed = []
for is_attribute, specifier in specifiers:
if previous is astroid.Uninferable:
break
parsed.append((is_attribute, specifier))
if is_attribute:
try:
previous = previous.getattr(specifier)[0]
except astroid.NotFoundError:
if (
hasattr(previous, "has_dynamic_getattr")
and previous.has_dynamic_getattr()
):
# Don't warn if the object has a custom __getattr__
break
path = get_access_path(key, parsed)
self.add_message(
"missing-format-attribute",
args=(specifier, path),
node=node,
)
break
else:
warn_error = _False
if hasattr(previous, "getitem"):
try:
previous = previous.getitem(nodes.Const(specifier))
except (
astroid.AstroidIndexError,
astroid.AstroidTypeError,
astroid.AttributeInferenceError,
):
warn_error = _True
except astroid.InferenceError:
break
if previous is astroid.Uninferable:
break
else:
try:
# Lookup __getitem__ in the current node,
# but skip further checks, because we can't
# retrieve the looked object
previous.getattr("__getitem__")
break
except astroid.NotFoundError:
warn_error = _True
if warn_error:
path = get_access_path(key, parsed)
self.add_message(
"invalid-format-index", args=(specifier, path), node=node
)
break
try:
previous = next(previous.infer())
except astroid.InferenceError:
# can't check further if we can't infer it
break
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 554 | get_argument_from_call | ref | function | argname = utils.get_argument_from_call(node, key)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 564 | safe_infer | ref | function | argument = utils.safe_infer(argname)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 587 | has_dynamic_getattr | ref | function | and previous.has_dynamic_getattr()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 591 | get_access_path | ref | function | path = get_access_path(key, parsed)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 592 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 602 | getitem | ref | function | previous = previous.getitem(nodes.Const(specifier))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 602 | Const | ref | function | previous = previous.getitem(nodes.Const(specifier))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 623 | get_access_path | ref | function | path = get_access_path(key, parsed)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 624 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 630 | infer | ref | function | previous = next(previous.infer())
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 636 | StringConstantChecker | def | class | __init__ process_module process_tokens visit_list visit_set visit_tuple visit_assign check_for_consistent_string_delimiters check_for_concatenated_strings process_string_token process_non_raw_string_token visit_const _detect_u_string_prefix |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 715 | process_module | def | function | def process_module(self, node: nodes.Module) -> None:
self._unicode_literals = "unicode_literals" in node.future_imports
def process_tokens(self, tokens):
encoding = "ascii"
for i, (tok_type, token, start, _, line) in enumerate(tokens):
if tok_type == tokenize.ENCODING:
# this is always the first token processed
encoding = token
elif tok_type == tokenize.STRING:
# 'token' is the whole un-parsed token; we can look at the start
# of it to see whether it's a raw or unicode string etc.
self.process_string_token(token, start[0], start[1])
# We figure the next token, ignoring comments & newlines:
j = i + 1
while j < len(tokens) and tokens[j].type in (
tokenize.NEWLINE,
tokenize.NL,
tokenize.COMMENT,
):
j += 1
next_token = tokens[j] if j < len(tokens) else None
if encoding != "ascii":
# We convert `tokenize` character count into a byte count,
# to match with astroid `.col_offset`
start = (start[0], len(line[: start[1]].encode(encoding)))
self.string_tokens[start] = (str_eval(token), next_token)
if self.config.check_quote_consistency:
self.check_for_consistent_string_delimiters(tokens)
@check_messages("implicit-str-concat")
def visit_list(self, node: nodes.List) -> None:
self.check_for_concatenated_strings(node.elts, "list")
@check_messages("implicit-str-concat")
def visit_set(self, node: nodes.Set) -> None:
self.check_for_concatenated_strings(node.elts, "set")
@check_messages("implicit-str-concat")
def visit_tuple(self, node: nodes.Tuple) -> None:
self.check_for_concatenated_strings(node.elts, "tuple")
def visit_assign(self, node: nodes.Assign) -> None:
if isinstance(node.value, nodes.Const) and isinstance(node.value.value, str):
self.check_for_concatenated_strings([node.value], "assignment")
def check_for_consistent_string_delimiters(
self, tokens: Iterable[tokenize.TokenInfo]
) -> None:
"""Adds a message for each string using inconsistent quote delimiters.
Quote delimiters are used inconsistently if " and ' are mixed in a module's
shortstrings without having done so to avoid escaping an internal quote
character.
Args:
tokens: The tokens to be checked against for consistent usage.
"""
string_delimiters: Counter[str] = collections.Counter()
# First, figure out which quote character predominates in the module
for tok_type, token, _, _, _ in tokens:
if tok_type == tokenize.STRING and _is_quote_delimiter_chosen_freely(token):
string_delimiters[_get_quote_delimiter(token)] += 1
if len(string_delimiters) > 1:
# Ties are broken arbitrarily
most_common_delimiter = string_delimiters.most_common(1)[0][0]
for tok_type, token, start, _, _ in tokens:
if tok_type != tokenize.STRING:
continue
quote_delimiter = _get_quote_delimiter(token)
if (
_is_quote_delimiter_chosen_freely(token)
and quote_delimiter != most_common_delimiter
):
self.add_message(
"inconsistent-quotes", line=start[0], args=(quote_delimiter,)
)
def check_for_concatenated_strings(self, elements, iterable_type):
for elt in elements:
if not (
isinstance(elt, nodes.Const) and elt.pytype() in _AST_NODE_STR_TYPES
):
continue
if elt.col_offset < 0:
# This can happen in case of escaped newlines
continue
if (elt.lineno, elt.col_offset) not in self.string_tokens:
# This may happen with Latin1 encoding
# cf. https://github.com/PyCQA/pylint/issues/2610
continue
matching_token, next_token = self.string_tokens[
(elt.lineno, elt.col_offset)
]
# We detect string concatenation: the AST Const is the
# combination of 2 string tokens
if matching_token != elt.value and next_token is not None:
if next_token.type == tokenize.STRING and (
next_token.start[0] == elt.lineno
or self.config.check_str_concat_over_line_jumps
):
self.add_message(
"implicit-str-concat", line=elt.lineno, args=(iterable_type,)
)
def process_string_token(self, token, start_row, start_col):
quote_char = None
index = None
for index, char in enumerate(token):
if char in "'\"":
quote_char = char
break
if quote_char is None:
return
prefix = token[:index].lower() # markers like u, b, r.
after_prefix = token[index:]
# Chop off quotes
quote_length = (
3 if after_prefix[:3] == after_prefix[-3:] == 3 * quote_char else 1
)
string_body = after_prefix[quote_length:-quote_length]
# No special checks on raw strings at the moment.
if "r" not in prefix:
self.process_non_raw_string_token(
prefix,
string_body,
start_row,
start_col + len(prefix) + quote_length,
)
def process_non_raw_string_token(
self, prefix, string_body, start_row, string_start_col
):
"""Check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line number in the source.
string_start_col: integer col number of the string start in the source.
"""
# Walk through the string; if we see a backslash then escape the next
# character, and skip over it. If we see a non-escaped character,
# alert, and continue.
#
# Accept a backslash when it escapes a backslash, or a quote, or
# end-of-line, or one of the letters that introduce a special escape
# sequence <https://docs.python.org/reference/lexical_analysis.html>
#
index = 0
while _True:
index = string_body.find("\\", index)
if index == -1:
break
# There must be a next character; having a backslash at the end
# of the string would be a SyntaxError.
next_char = string_body[index + 1]
match = string_body[index : index + 2]
# The column offset will vary depending on whether the string token
# is broken across lines. Calculate relative to the nearest line
# break or relative to the start of the token's line.
last_newline = string_body.rfind("\n", 0, index)
if last_newline == -1:
line = start_row
col_offset = index + string_start_col
else:
line = start_row + string_body.count("\n", 0, index)
col_offset = index - last_newline - 1
if next_char in self.UNICODE_ESCAPE_CHARACTERS:
if "u" in prefix:
pass
elif "b" not in prefix:
pass # unicode by default
else:
self.add_message(
"anomalous-unicode-escape-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
elif next_char not in self.ESCAPE_CHARACTERS:
self.add_message(
"anomalous-backslash-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
# Whether it was a valid escape or not, backslash followed by
# another character can always be consumed whole: the second
# character can never be the start of a new backslash escape.
index += 2
@check_messages("redundant-u-string-prefix")
def visit_const(self, node: nodes.Const) -> None:
if node.pytype() == "builtins.str" and not isinstance(
node.parent, nodes.JoinedStr
):
self._detect_u_string_prefix(node)
def _detect_u_string_prefix(self, node: nodes.Const):
"""Check whether strings include a 'u' prefix like u'String'."""
if node.kind == "u":
self.add_message(
"redundant-u-string-prefix",
line=node.lineno,
col_offset=node.col_offset,
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 718 | process_tokens | def | function | def process_tokens(self, tokens):
encoding = "ascii"
for i, (tok_type, token, start, _, line) in enumerate(tokens):
if tok_type == tokenize.ENCODING:
# this is always the first token processed
encoding = token
elif tok_type == tokenize.STRING:
# 'token' is the whole un-parsed token; we can look at the start
# of it to see whether it's a raw or unicode string etc.
self.process_string_token(token, start[0], start[1])
# We figure the next token, ignoring comments & newlines:
j = i + 1
while j < len(tokens) and tokens[j].type in (
tokenize.NEWLINE,
tokenize.NL,
tokenize.COMMENT,
):
j += 1
next_token = tokens[j] if j < len(tokens) else None
if encoding != "ascii":
# We convert `tokenize` character count into a byte count,
# to match with astroid `.col_offset`
start = (start[0], len(line[: start[1]].encode(encoding)))
self.string_tokens[start] = (str_eval(token), next_token)
if self.config.check_quote_consistency:
self.check_for_consistent_string_delimiters(tokens)
@check_messages("implicit-str-concat")
def visit_list(self, node: nodes.List) -> None:
self.check_for_concatenated_strings(node.elts, "list")
@check_messages("implicit-str-concat")
def visit_set(self, node: nodes.Set) -> None:
self.check_for_concatenated_strings(node.elts, "set")
@check_messages("implicit-str-concat")
def visit_tuple(self, node: nodes.Tuple) -> None:
self.check_for_concatenated_strings(node.elts, "tuple")
def visit_assign(self, node: nodes.Assign) -> None:
if isinstance(node.value, nodes.Const) and isinstance(node.value.value, str):
self.check_for_concatenated_strings([node.value], "assignment")
def check_for_consistent_string_delimiters(
self, tokens: Iterable[tokenize.TokenInfo]
) -> None:
"""Adds a message for each string using inconsistent quote delimiters.
Quote delimiters are used inconsistently if " and ' are mixed in a module's
shortstrings without having done so to avoid escaping an internal quote
character.
Args:
tokens: The tokens to be checked against for consistent usage.
"""
string_delimiters: Counter[str] = collections.Counter()
# First, figure out which quote character predominates in the module
for tok_type, token, _, _, _ in tokens:
if tok_type == tokenize.STRING and _is_quote_delimiter_chosen_freely(token):
string_delimiters[_get_quote_delimiter(token)] += 1
if len(string_delimiters) > 1:
# Ties are broken arbitrarily
most_common_delimiter = string_delimiters.most_common(1)[0][0]
for tok_type, token, start, _, _ in tokens:
if tok_type != tokenize.STRING:
continue
quote_delimiter = _get_quote_delimiter(token)
if (
_is_quote_delimiter_chosen_freely(token)
and quote_delimiter != most_common_delimiter
):
self.add_message(
"inconsistent-quotes", line=start[0], args=(quote_delimiter,)
)
def check_for_concatenated_strings(self, elements, iterable_type):
for elt in elements:
if not (
isinstance(elt, nodes.Const) and elt.pytype() in _AST_NODE_STR_TYPES
):
continue
if elt.col_offset < 0:
# This can happen in case of escaped newlines
continue
if (elt.lineno, elt.col_offset) not in self.string_tokens:
# This may happen with Latin1 encoding
# cf. https://github.com/PyCQA/pylint/issues/2610
continue
matching_token, next_token = self.string_tokens[
(elt.lineno, elt.col_offset)
]
# We detect string concatenation: the AST Const is the
# combination of 2 string tokens
if matching_token != elt.value and next_token is not None:
if next_token.type == tokenize.STRING and (
next_token.start[0] == elt.lineno
or self.config.check_str_concat_over_line_jumps
):
self.add_message(
"implicit-str-concat", line=elt.lineno, args=(iterable_type,)
)
def process_string_token(self, token, start_row, start_col):
quote_char = None
index = None
for index, char in enumerate(token):
if char in "'\"":
quote_char = char
break
if quote_char is None:
return
prefix = token[:index].lower() # markers like u, b, r.
after_prefix = token[index:]
# Chop off quotes
quote_length = (
3 if after_prefix[:3] == after_prefix[-3:] == 3 * quote_char else 1
)
string_body = after_prefix[quote_length:-quote_length]
# No special checks on raw strings at the moment.
if "r" not in prefix:
self.process_non_raw_string_token(
prefix,
string_body,
start_row,
start_col + len(prefix) + quote_length,
)
def process_non_raw_string_token(
self, prefix, string_body, start_row, string_start_col
):
"""Check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line number in the source.
string_start_col: integer col number of the string start in the source.
"""
# Walk through the string; if we see a backslash then escape the next
# character, and skip over it. If we see a non-escaped character,
# alert, and continue.
#
# Accept a backslash when it escapes a backslash, or a quote, or
# end-of-line, or one of the letters that introduce a special escape
# sequence <https://docs.python.org/reference/lexical_analysis.html>
#
index = 0
while _True:
index = string_body.find("\\", index)
if index == -1:
break
# There must be a next character; having a backslash at the end
# of the string would be a SyntaxError.
next_char = string_body[index + 1]
match = string_body[index : index + 2]
# The column offset will vary depending on whether the string token
# is broken across lines. Calculate relative to the nearest line
# break or relative to the start of the token's line.
last_newline = string_body.rfind("\n", 0, index)
if last_newline == -1:
line = start_row
col_offset = index + string_start_col
else:
line = start_row + string_body.count("\n", 0, index)
col_offset = index - last_newline - 1
if next_char in self.UNICODE_ESCAPE_CHARACTERS:
if "u" in prefix:
pass
elif "b" not in prefix:
pass # unicode by default
else:
self.add_message(
"anomalous-unicode-escape-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
elif next_char not in self.ESCAPE_CHARACTERS:
self.add_message(
"anomalous-backslash-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
# Whether it was a valid escape or not, backslash followed by
# another character can always be consumed whole: the second
# character can never be the start of a new backslash escape.
index += 2
@check_messages("redundant-u-string-prefix")
def visit_const(self, node: nodes.Const) -> None:
if node.pytype() == "builtins.str" and not isinstance(
node.parent, nodes.JoinedStr
):
self._detect_u_string_prefix(node)
def _detect_u_string_prefix(self, node: nodes.Const):
"""Check whether strings include a 'u' prefix like u'String'."""
if node.kind == "u":
self.add_message(
"redundant-u-string-prefix",
line=node.lineno,
col_offset=node.col_offset,
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 727 | process_string_token | ref | function | self.process_string_token(token, start[0], start[1])
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 741 | str_eval | ref | function | self.string_tokens[start] = (str_eval(token), next_token)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 744 | check_for_consistent_string_delimiters | ref | function | self.check_for_consistent_string_delimiters(tokens)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 746 | check_messages | ref | function | @check_messages("implicit-str-concat")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 747 | visit_list | def | function | def visit_list(self, node: nodes.List) -> None:
self.check_for_concatenated_strings(node.elts, "list")
@check_messages("implicit-str-concat")
def visit_set(self, node: nodes.Set) -> None:
self.check_for_concatenated_strings(node.elts, "set")
@check_messages("implicit-str-concat")
def visit_tuple(self, node: nodes.Tuple) -> None:
self.check_for_concatenated_strings(node.elts, "tuple")
def visit_assign(self, node: nodes.Assign) -> None:
if isinstance(node.value, nodes.Const) and isinstance(node.value.value, str):
self.check_for_concatenated_strings([node.value], "assignment")
def check_for_consistent_string_delimiters(
self, tokens: Iterable[tokenize.TokenInfo]
) -> None:
"""Adds a message for each string using inconsistent quote delimiters.
Quote delimiters are used inconsistently if " and ' are mixed in a module's
shortstrings without having done so to avoid escaping an internal quote
character.
Args:
tokens: The tokens to be checked against for consistent usage.
"""
string_delimiters: Counter[str] = collections.Counter()
# First, figure out which quote character predominates in the module
for tok_type, token, _, _, _ in tokens:
if tok_type == tokenize.STRING and _is_quote_delimiter_chosen_freely(token):
string_delimiters[_get_quote_delimiter(token)] += 1
if len(string_delimiters) > 1:
# Ties are broken arbitrarily
most_common_delimiter = string_delimiters.most_common(1)[0][0]
for tok_type, token, start, _, _ in tokens:
if tok_type != tokenize.STRING:
continue
quote_delimiter = _get_quote_delimiter(token)
if (
_is_quote_delimiter_chosen_freely(token)
and quote_delimiter != most_common_delimiter
):
self.add_message(
"inconsistent-quotes", line=start[0], args=(quote_delimiter,)
)
def check_for_concatenated_strings(self, elements, iterable_type):
for elt in elements:
if not (
isinstance(elt, nodes.Const) and elt.pytype() in _AST_NODE_STR_TYPES
):
continue
if elt.col_offset < 0:
# This can happen in case of escaped newlines
continue
if (elt.lineno, elt.col_offset) not in self.string_tokens:
# This may happen with Latin1 encoding
# cf. https://github.com/PyCQA/pylint/issues/2610
continue
matching_token, next_token = self.string_tokens[
(elt.lineno, elt.col_offset)
]
# We detect string concatenation: the AST Const is the
# combination of 2 string tokens
if matching_token != elt.value and next_token is not None:
if next_token.type == tokenize.STRING and (
next_token.start[0] == elt.lineno
or self.config.check_str_concat_over_line_jumps
):
self.add_message(
"implicit-str-concat", line=elt.lineno, args=(iterable_type,)
)
def process_string_token(self, token, start_row, start_col):
quote_char = None
index = None
for index, char in enumerate(token):
if char in "'\"":
quote_char = char
break
if quote_char is None:
return
prefix = token[:index].lower() # markers like u, b, r.
after_prefix = token[index:]
# Chop off quotes
quote_length = (
3 if after_prefix[:3] == after_prefix[-3:] == 3 * quote_char else 1
)
string_body = after_prefix[quote_length:-quote_length]
# No special checks on raw strings at the moment.
if "r" not in prefix:
self.process_non_raw_string_token(
prefix,
string_body,
start_row,
start_col + len(prefix) + quote_length,
)
def process_non_raw_string_token(
self, prefix, string_body, start_row, string_start_col
):
"""Check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line number in the source.
string_start_col: integer col number of the string start in the source.
"""
# Walk through the string; if we see a backslash then escape the next
# character, and skip over it. If we see a non-escaped character,
# alert, and continue.
#
# Accept a backslash when it escapes a backslash, or a quote, or
# end-of-line, or one of the letters that introduce a special escape
# sequence <https://docs.python.org/reference/lexical_analysis.html>
#
index = 0
while _True:
index = string_body.find("\\", index)
if index == -1:
break
# There must be a next character; having a backslash at the end
# of the string would be a SyntaxError.
next_char = string_body[index + 1]
match = string_body[index : index + 2]
# The column offset will vary depending on whether the string token
# is broken across lines. Calculate relative to the nearest line
# break or relative to the start of the token's line.
last_newline = string_body.rfind("\n", 0, index)
if last_newline == -1:
line = start_row
col_offset = index + string_start_col
else:
line = start_row + string_body.count("\n", 0, index)
col_offset = index - last_newline - 1
if next_char in self.UNICODE_ESCAPE_CHARACTERS:
if "u" in prefix:
pass
elif "b" not in prefix:
pass # unicode by default
else:
self.add_message(
"anomalous-unicode-escape-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
elif next_char not in self.ESCAPE_CHARACTERS:
self.add_message(
"anomalous-backslash-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
# Whether it was a valid escape or not, backslash followed by
# another character can always be consumed whole: the second
# character can never be the start of a new backslash escape.
index += 2
@check_messages("redundant-u-string-prefix")
def visit_const(self, node: nodes.Const) -> None:
if node.pytype() == "builtins.str" and not isinstance(
node.parent, nodes.JoinedStr
):
self._detect_u_string_prefix(node)
def _detect_u_string_prefix(self, node: nodes.Const):
"""Check whether strings include a 'u' prefix like u'String'."""
if node.kind == "u":
self.add_message(
"redundant-u-string-prefix",
line=node.lineno,
col_offset=node.col_offset,
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 748 | check_for_concatenated_strings | ref | function | self.check_for_concatenated_strings(node.elts, "list")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 750 | check_messages | ref | function | @check_messages("implicit-str-concat")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 751 | visit_set | def | function | def visit_set(self, node: nodes.Set) -> None:
self.check_for_concatenated_strings(node.elts, "set")
@check_messages("implicit-str-concat")
def visit_tuple(self, node: nodes.Tuple) -> None:
self.check_for_concatenated_strings(node.elts, "tuple")
def visit_assign(self, node: nodes.Assign) -> None:
if isinstance(node.value, nodes.Const) and isinstance(node.value.value, str):
self.check_for_concatenated_strings([node.value], "assignment")
def check_for_consistent_string_delimiters(
self, tokens: Iterable[tokenize.TokenInfo]
) -> None:
"""Adds a message for each string using inconsistent quote delimiters.
Quote delimiters are used inconsistently if " and ' are mixed in a module's
shortstrings without having done so to avoid escaping an internal quote
character.
Args:
tokens: The tokens to be checked against for consistent usage.
"""
string_delimiters: Counter[str] = collections.Counter()
# First, figure out which quote character predominates in the module
for tok_type, token, _, _, _ in tokens:
if tok_type == tokenize.STRING and _is_quote_delimiter_chosen_freely(token):
string_delimiters[_get_quote_delimiter(token)] += 1
if len(string_delimiters) > 1:
# Ties are broken arbitrarily
most_common_delimiter = string_delimiters.most_common(1)[0][0]
for tok_type, token, start, _, _ in tokens:
if tok_type != tokenize.STRING:
continue
quote_delimiter = _get_quote_delimiter(token)
if (
_is_quote_delimiter_chosen_freely(token)
and quote_delimiter != most_common_delimiter
):
self.add_message(
"inconsistent-quotes", line=start[0], args=(quote_delimiter,)
)
def check_for_concatenated_strings(self, elements, iterable_type):
for elt in elements:
if not (
isinstance(elt, nodes.Const) and elt.pytype() in _AST_NODE_STR_TYPES
):
continue
if elt.col_offset < 0:
# This can happen in case of escaped newlines
continue
if (elt.lineno, elt.col_offset) not in self.string_tokens:
# This may happen with Latin1 encoding
# cf. https://github.com/PyCQA/pylint/issues/2610
continue
matching_token, next_token = self.string_tokens[
(elt.lineno, elt.col_offset)
]
# We detect string concatenation: the AST Const is the
# combination of 2 string tokens
if matching_token != elt.value and next_token is not None:
if next_token.type == tokenize.STRING and (
next_token.start[0] == elt.lineno
or self.config.check_str_concat_over_line_jumps
):
self.add_message(
"implicit-str-concat", line=elt.lineno, args=(iterable_type,)
)
def process_string_token(self, token, start_row, start_col):
quote_char = None
index = None
for index, char in enumerate(token):
if char in "'\"":
quote_char = char
break
if quote_char is None:
return
prefix = token[:index].lower() # markers like u, b, r.
after_prefix = token[index:]
# Chop off quotes
quote_length = (
3 if after_prefix[:3] == after_prefix[-3:] == 3 * quote_char else 1
)
string_body = after_prefix[quote_length:-quote_length]
# No special checks on raw strings at the moment.
if "r" not in prefix:
self.process_non_raw_string_token(
prefix,
string_body,
start_row,
start_col + len(prefix) + quote_length,
)
def process_non_raw_string_token(
self, prefix, string_body, start_row, string_start_col
):
"""Check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line number in the source.
string_start_col: integer col number of the string start in the source.
"""
# Walk through the string; if we see a backslash then escape the next
# character, and skip over it. If we see a non-escaped character,
# alert, and continue.
#
# Accept a backslash when it escapes a backslash, or a quote, or
# end-of-line, or one of the letters that introduce a special escape
# sequence <https://docs.python.org/reference/lexical_analysis.html>
#
index = 0
while _True:
index = string_body.find("\\", index)
if index == -1:
break
# There must be a next character; having a backslash at the end
# of the string would be a SyntaxError.
next_char = string_body[index + 1]
match = string_body[index : index + 2]
# The column offset will vary depending on whether the string token
# is broken across lines. Calculate relative to the nearest line
# break or relative to the start of the token's line.
last_newline = string_body.rfind("\n", 0, index)
if last_newline == -1:
line = start_row
col_offset = index + string_start_col
else:
line = start_row + string_body.count("\n", 0, index)
col_offset = index - last_newline - 1
if next_char in self.UNICODE_ESCAPE_CHARACTERS:
if "u" in prefix:
pass
elif "b" not in prefix:
pass # unicode by default
else:
self.add_message(
"anomalous-unicode-escape-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
elif next_char not in self.ESCAPE_CHARACTERS:
self.add_message(
"anomalous-backslash-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
# Whether it was a valid escape or not, backslash followed by
# another character can always be consumed whole: the second
# character can never be the start of a new backslash escape.
index += 2
@check_messages("redundant-u-string-prefix")
def visit_const(self, node: nodes.Const) -> None:
if node.pytype() == "builtins.str" and not isinstance(
node.parent, nodes.JoinedStr
):
self._detect_u_string_prefix(node)
def _detect_u_string_prefix(self, node: nodes.Const):
"""Check whether strings include a 'u' prefix like u'String'."""
if node.kind == "u":
self.add_message(
"redundant-u-string-prefix",
line=node.lineno,
col_offset=node.col_offset,
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 752 | check_for_concatenated_strings | ref | function | self.check_for_concatenated_strings(node.elts, "set")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 754 | check_messages | ref | function | @check_messages("implicit-str-concat")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 755 | visit_tuple | def | function | def visit_tuple(self, node: nodes.Tuple) -> None:
self.check_for_concatenated_strings(node.elts, "tuple")
def visit_assign(self, node: nodes.Assign) -> None:
if isinstance(node.value, nodes.Const) and isinstance(node.value.value, str):
self.check_for_concatenated_strings([node.value], "assignment")
def check_for_consistent_string_delimiters(
self, tokens: Iterable[tokenize.TokenInfo]
) -> None:
"""Adds a message for each string using inconsistent quote delimiters.
Quote delimiters are used inconsistently if " and ' are mixed in a module's
shortstrings without having done so to avoid escaping an internal quote
character.
Args:
tokens: The tokens to be checked against for consistent usage.
"""
string_delimiters: Counter[str] = collections.Counter()
# First, figure out which quote character predominates in the module
for tok_type, token, _, _, _ in tokens:
if tok_type == tokenize.STRING and _is_quote_delimiter_chosen_freely(token):
string_delimiters[_get_quote_delimiter(token)] += 1
if len(string_delimiters) > 1:
# Ties are broken arbitrarily
most_common_delimiter = string_delimiters.most_common(1)[0][0]
for tok_type, token, start, _, _ in tokens:
if tok_type != tokenize.STRING:
continue
quote_delimiter = _get_quote_delimiter(token)
if (
_is_quote_delimiter_chosen_freely(token)
and quote_delimiter != most_common_delimiter
):
self.add_message(
"inconsistent-quotes", line=start[0], args=(quote_delimiter,)
)
def check_for_concatenated_strings(self, elements, iterable_type):
for elt in elements:
if not (
isinstance(elt, nodes.Const) and elt.pytype() in _AST_NODE_STR_TYPES
):
continue
if elt.col_offset < 0:
# This can happen in case of escaped newlines
continue
if (elt.lineno, elt.col_offset) not in self.string_tokens:
# This may happen with Latin1 encoding
# cf. https://github.com/PyCQA/pylint/issues/2610
continue
matching_token, next_token = self.string_tokens[
(elt.lineno, elt.col_offset)
]
# We detect string concatenation: the AST Const is the
# combination of 2 string tokens
if matching_token != elt.value and next_token is not None:
if next_token.type == tokenize.STRING and (
next_token.start[0] == elt.lineno
or self.config.check_str_concat_over_line_jumps
):
self.add_message(
"implicit-str-concat", line=elt.lineno, args=(iterable_type,)
)
def process_string_token(self, token, start_row, start_col):
quote_char = None
index = None
for index, char in enumerate(token):
if char in "'\"":
quote_char = char
break
if quote_char is None:
return
prefix = token[:index].lower() # markers like u, b, r.
after_prefix = token[index:]
# Chop off quotes
quote_length = (
3 if after_prefix[:3] == after_prefix[-3:] == 3 * quote_char else 1
)
string_body = after_prefix[quote_length:-quote_length]
# No special checks on raw strings at the moment.
if "r" not in prefix:
self.process_non_raw_string_token(
prefix,
string_body,
start_row,
start_col + len(prefix) + quote_length,
)
def process_non_raw_string_token(
self, prefix, string_body, start_row, string_start_col
):
"""Check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line number in the source.
string_start_col: integer col number of the string start in the source.
"""
# Walk through the string; if we see a backslash then escape the next
# character, and skip over it. If we see a non-escaped character,
# alert, and continue.
#
# Accept a backslash when it escapes a backslash, or a quote, or
# end-of-line, or one of the letters that introduce a special escape
# sequence <https://docs.python.org/reference/lexical_analysis.html>
#
index = 0
while _True:
index = string_body.find("\\", index)
if index == -1:
break
# There must be a next character; having a backslash at the end
# of the string would be a SyntaxError.
next_char = string_body[index + 1]
match = string_body[index : index + 2]
# The column offset will vary depending on whether the string token
# is broken across lines. Calculate relative to the nearest line
# break or relative to the start of the token's line.
last_newline = string_body.rfind("\n", 0, index)
if last_newline == -1:
line = start_row
col_offset = index + string_start_col
else:
line = start_row + string_body.count("\n", 0, index)
col_offset = index - last_newline - 1
if next_char in self.UNICODE_ESCAPE_CHARACTERS:
if "u" in prefix:
pass
elif "b" not in prefix:
pass # unicode by default
else:
self.add_message(
"anomalous-unicode-escape-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
elif next_char not in self.ESCAPE_CHARACTERS:
self.add_message(
"anomalous-backslash-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
# Whether it was a valid escape or not, backslash followed by
# another character can always be consumed whole: the second
# character can never be the start of a new backslash escape.
index += 2
@check_messages("redundant-u-string-prefix")
def visit_const(self, node: nodes.Const) -> None:
if node.pytype() == "builtins.str" and not isinstance(
node.parent, nodes.JoinedStr
):
self._detect_u_string_prefix(node)
def _detect_u_string_prefix(self, node: nodes.Const):
"""Check whether strings include a 'u' prefix like u'String'."""
if node.kind == "u":
self.add_message(
"redundant-u-string-prefix",
line=node.lineno,
col_offset=node.col_offset,
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 756 | check_for_concatenated_strings | ref | function | self.check_for_concatenated_strings(node.elts, "tuple")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 758 | visit_assign | def | function | def visit_assign(self, node: nodes.Assign) -> None:
if isinstance(node.value, nodes.Const) and isinstance(node.value.value, str):
self.check_for_concatenated_strings([node.value], "assignment")
def check_for_consistent_string_delimiters(
self, tokens: Iterable[tokenize.TokenInfo]
) -> None:
"""Adds a message for each string using inconsistent quote delimiters.
Quote delimiters are used inconsistently if " and ' are mixed in a module's
shortstrings without having done so to avoid escaping an internal quote
character.
Args:
tokens: The tokens to be checked against for consistent usage.
"""
string_delimiters: Counter[str] = collections.Counter()
# First, figure out which quote character predominates in the module
for tok_type, token, _, _, _ in tokens:
if tok_type == tokenize.STRING and _is_quote_delimiter_chosen_freely(token):
string_delimiters[_get_quote_delimiter(token)] += 1
if len(string_delimiters) > 1:
# Ties are broken arbitrarily
most_common_delimiter = string_delimiters.most_common(1)[0][0]
for tok_type, token, start, _, _ in tokens:
if tok_type != tokenize.STRING:
continue
quote_delimiter = _get_quote_delimiter(token)
if (
_is_quote_delimiter_chosen_freely(token)
and quote_delimiter != most_common_delimiter
):
self.add_message(
"inconsistent-quotes", line=start[0], args=(quote_delimiter,)
)
def check_for_concatenated_strings(self, elements, iterable_type):
for elt in elements:
if not (
isinstance(elt, nodes.Const) and elt.pytype() in _AST_NODE_STR_TYPES
):
continue
if elt.col_offset < 0:
# This can happen in case of escaped newlines
continue
if (elt.lineno, elt.col_offset) not in self.string_tokens:
# This may happen with Latin1 encoding
# cf. https://github.com/PyCQA/pylint/issues/2610
continue
matching_token, next_token = self.string_tokens[
(elt.lineno, elt.col_offset)
]
# We detect string concatenation: the AST Const is the
# combination of 2 string tokens
if matching_token != elt.value and next_token is not None:
if next_token.type == tokenize.STRING and (
next_token.start[0] == elt.lineno
or self.config.check_str_concat_over_line_jumps
):
self.add_message(
"implicit-str-concat", line=elt.lineno, args=(iterable_type,)
)
def process_string_token(self, token, start_row, start_col):
quote_char = None
index = None
for index, char in enumerate(token):
if char in "'\"":
quote_char = char
break
if quote_char is None:
return
prefix = token[:index].lower() # markers like u, b, r.
after_prefix = token[index:]
# Chop off quotes
quote_length = (
3 if after_prefix[:3] == after_prefix[-3:] == 3 * quote_char else 1
)
string_body = after_prefix[quote_length:-quote_length]
# No special checks on raw strings at the moment.
if "r" not in prefix:
self.process_non_raw_string_token(
prefix,
string_body,
start_row,
start_col + len(prefix) + quote_length,
)
def process_non_raw_string_token(
self, prefix, string_body, start_row, string_start_col
):
"""Check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line number in the source.
string_start_col: integer col number of the string start in the source.
"""
# Walk through the string; if we see a backslash then escape the next
# character, and skip over it. If we see a non-escaped character,
# alert, and continue.
#
# Accept a backslash when it escapes a backslash, or a quote, or
# end-of-line, or one of the letters that introduce a special escape
# sequence <https://docs.python.org/reference/lexical_analysis.html>
#
index = 0
while _True:
index = string_body.find("\\", index)
if index == -1:
break
# There must be a next character; having a backslash at the end
# of the string would be a SyntaxError.
next_char = string_body[index + 1]
match = string_body[index : index + 2]
# The column offset will vary depending on whether the string token
# is broken across lines. Calculate relative to the nearest line
# break or relative to the start of the token's line.
last_newline = string_body.rfind("\n", 0, index)
if last_newline == -1:
line = start_row
col_offset = index + string_start_col
else:
line = start_row + string_body.count("\n", 0, index)
col_offset = index - last_newline - 1
if next_char in self.UNICODE_ESCAPE_CHARACTERS:
if "u" in prefix:
pass
elif "b" not in prefix:
pass # unicode by default
else:
self.add_message(
"anomalous-unicode-escape-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
elif next_char not in self.ESCAPE_CHARACTERS:
self.add_message(
"anomalous-backslash-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
# Whether it was a valid escape or not, backslash followed by
# another character can always be consumed whole: the second
# character can never be the start of a new backslash escape.
index += 2
@check_messages("redundant-u-string-prefix")
def visit_const(self, node: nodes.Const) -> None:
if node.pytype() == "builtins.str" and not isinstance(
node.parent, nodes.JoinedStr
):
self._detect_u_string_prefix(node)
def _detect_u_string_prefix(self, node: nodes.Const):
"""Check whether strings include a 'u' prefix like u'String'."""
if node.kind == "u":
self.add_message(
"redundant-u-string-prefix",
line=node.lineno,
col_offset=node.col_offset,
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 760 | check_for_concatenated_strings | ref | function | self.check_for_concatenated_strings([node.value], "assignment")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 762 | check_for_consistent_string_delimiters | def | function | def check_for_consistent_string_delimiters(
self, tokens: Iterable[tokenize.TokenInfo]
) -> None:
"""Adds a message for each string using inconsistent quote delimiters.
Quote delimiters are used inconsistently if " and ' are mixed in a module's
shortstrings without having done so to avoid escaping an internal quote
character.
Args:
tokens: The tokens to be checked against for consistent usage.
"""
string_delimiters: Counter[str] = collections.Counter()
# First, figure out which quote character predominates in the module
for tok_type, token, _, _, _ in tokens:
if tok_type == tokenize.STRING and _is_quote_delimiter_chosen_freely(token):
string_delimiters[_get_quote_delimiter(token)] += 1
if len(string_delimiters) > 1:
# Ties are broken arbitrarily
most_common_delimiter = string_delimiters.most_common(1)[0][0]
for tok_type, token, start, _, _ in tokens:
if tok_type != tokenize.STRING:
continue
quote_delimiter = _get_quote_delimiter(token)
if (
_is_quote_delimiter_chosen_freely(token)
and quote_delimiter != most_common_delimiter
):
self.add_message(
"inconsistent-quotes", line=start[0], args=(quote_delimiter,)
)
def check_for_concatenated_strings(self, elements, iterable_type):
for elt in elements:
if not (
isinstance(elt, nodes.Const) and elt.pytype() in _AST_NODE_STR_TYPES
):
continue
if elt.col_offset < 0:
# This can happen in case of escaped newlines
continue
if (elt.lineno, elt.col_offset) not in self.string_tokens:
# This may happen with Latin1 encoding
# cf. https://github.com/PyCQA/pylint/issues/2610
continue
matching_token, next_token = self.string_tokens[
(elt.lineno, elt.col_offset)
]
# We detect string concatenation: the AST Const is the
# combination of 2 string tokens
if matching_token != elt.value and next_token is not None:
if next_token.type == tokenize.STRING and (
next_token.start[0] == elt.lineno
or self.config.check_str_concat_over_line_jumps
):
self.add_message(
"implicit-str-concat", line=elt.lineno, args=(iterable_type,)
)
def process_string_token(self, token, start_row, start_col):
quote_char = None
index = None
for index, char in enumerate(token):
if char in "'\"":
quote_char = char
break
if quote_char is None:
return
prefix = token[:index].lower() # markers like u, b, r.
after_prefix = token[index:]
# Chop off quotes
quote_length = (
3 if after_prefix[:3] == after_prefix[-3:] == 3 * quote_char else 1
)
string_body = after_prefix[quote_length:-quote_length]
# No special checks on raw strings at the moment.
if "r" not in prefix:
self.process_non_raw_string_token(
prefix,
string_body,
start_row,
start_col + len(prefix) + quote_length,
)
def process_non_raw_string_token(
self, prefix, string_body, start_row, string_start_col
):
"""Check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line number in the source.
string_start_col: integer col number of the string start in the source.
"""
# Walk through the string; if we see a backslash then escape the next
# character, and skip over it. If we see a non-escaped character,
# alert, and continue.
#
# Accept a backslash when it escapes a backslash, or a quote, or
# end-of-line, or one of the letters that introduce a special escape
# sequence <https://docs.python.org/reference/lexical_analysis.html>
#
index = 0
while _True:
index = string_body.find("\\", index)
if index == -1:
break
# There must be a next character; having a backslash at the end
# of the string would be a SyntaxError.
next_char = string_body[index + 1]
match = string_body[index : index + 2]
# The column offset will vary depending on whether the string token
# is broken across lines. Calculate relative to the nearest line
# break or relative to the start of the token's line.
last_newline = string_body.rfind("\n", 0, index)
if last_newline == -1:
line = start_row
col_offset = index + string_start_col
else:
line = start_row + string_body.count("\n", 0, index)
col_offset = index - last_newline - 1
if next_char in self.UNICODE_ESCAPE_CHARACTERS:
if "u" in prefix:
pass
elif "b" not in prefix:
pass # unicode by default
else:
self.add_message(
"anomalous-unicode-escape-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
elif next_char not in self.ESCAPE_CHARACTERS:
self.add_message(
"anomalous-backslash-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
# Whether it was a valid escape or not, backslash followed by
# another character can always be consumed whole: the second
# character can never be the start of a new backslash escape.
index += 2
@check_messages("redundant-u-string-prefix")
def visit_const(self, node: nodes.Const) -> None:
if node.pytype() == "builtins.str" and not isinstance(
node.parent, nodes.JoinedStr
):
self._detect_u_string_prefix(node)
def _detect_u_string_prefix(self, node: nodes.Const):
"""Check whether strings include a 'u' prefix like u'String'."""
if node.kind == "u":
self.add_message(
"redundant-u-string-prefix",
line=node.lineno,
col_offset=node.col_offset,
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 778 | _is_quote_delimiter_chosen_freely | ref | function | if tok_type == tokenize.STRING and _is_quote_delimiter_chosen_freely(token):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 779 | _get_quote_delimiter | ref | function | string_delimiters[_get_quote_delimiter(token)] += 1
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 783 | most_common | ref | function | most_common_delimiter = string_delimiters.most_common(1)[0][0]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 787 | _get_quote_delimiter | ref | function | quote_delimiter = _get_quote_delimiter(token)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 789 | _is_quote_delimiter_chosen_freely | ref | function | _is_quote_delimiter_chosen_freely(token)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 792 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 796 | check_for_concatenated_strings | def | function | def check_for_concatenated_strings(self, elements, iterable_type):
for elt in elements:
if not (
isinstance(elt, nodes.Const) and elt.pytype() in _AST_NODE_STR_TYPES
):
continue
if elt.col_offset < 0:
# This can happen in case of escaped newlines
continue
if (elt.lineno, elt.col_offset) not in self.string_tokens:
# This may happen with Latin1 encoding
# cf. https://github.com/PyCQA/pylint/issues/2610
continue
matching_token, next_token = self.string_tokens[
(elt.lineno, elt.col_offset)
]
# We detect string concatenation: the AST Const is the
# combination of 2 string tokens
if matching_token != elt.value and next_token is not None:
if next_token.type == tokenize.STRING and (
next_token.start[0] == elt.lineno
or self.config.check_str_concat_over_line_jumps
):
self.add_message(
"implicit-str-concat", line=elt.lineno, args=(iterable_type,)
)
def process_string_token(self, token, start_row, start_col):
quote_char = None
index = None
for index, char in enumerate(token):
if char in "'\"":
quote_char = char
break
if quote_char is None:
return
prefix = token[:index].lower() # markers like u, b, r.
after_prefix = token[index:]
# Chop off quotes
quote_length = (
3 if after_prefix[:3] == after_prefix[-3:] == 3 * quote_char else 1
)
string_body = after_prefix[quote_length:-quote_length]
# No special checks on raw strings at the moment.
if "r" not in prefix:
self.process_non_raw_string_token(
prefix,
string_body,
start_row,
start_col + len(prefix) + quote_length,
)
def process_non_raw_string_token(
self, prefix, string_body, start_row, string_start_col
):
"""Check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line number in the source.
string_start_col: integer col number of the string start in the source.
"""
# Walk through the string; if we see a backslash then escape the next
# character, and skip over it. If we see a non-escaped character,
# alert, and continue.
#
# Accept a backslash when it escapes a backslash, or a quote, or
# end-of-line, or one of the letters that introduce a special escape
# sequence <https://docs.python.org/reference/lexical_analysis.html>
#
index = 0
while _True:
index = string_body.find("\\", index)
if index == -1:
break
# There must be a next character; having a backslash at the end
# of the string would be a SyntaxError.
next_char = string_body[index + 1]
match = string_body[index : index + 2]
# The column offset will vary depending on whether the string token
# is broken across lines. Calculate relative to the nearest line
# break or relative to the start of the token's line.
last_newline = string_body.rfind("\n", 0, index)
if last_newline == -1:
line = start_row
col_offset = index + string_start_col
else:
line = start_row + string_body.count("\n", 0, index)
col_offset = index - last_newline - 1
if next_char in self.UNICODE_ESCAPE_CHARACTERS:
if "u" in prefix:
pass
elif "b" not in prefix:
pass # unicode by default
else:
self.add_message(
"anomalous-unicode-escape-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
elif next_char not in self.ESCAPE_CHARACTERS:
self.add_message(
"anomalous-backslash-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
# Whether it was a valid escape or not, backslash followed by
# another character can always be consumed whole: the second
# character can never be the start of a new backslash escape.
index += 2
@check_messages("redundant-u-string-prefix")
def visit_const(self, node: nodes.Const) -> None:
if node.pytype() == "builtins.str" and not isinstance(
node.parent, nodes.JoinedStr
):
self._detect_u_string_prefix(node)
def _detect_u_string_prefix(self, node: nodes.Const):
"""Check whether strings include a 'u' prefix like u'String'."""
if node.kind == "u":
self.add_message(
"redundant-u-string-prefix",
line=node.lineno,
col_offset=node.col_offset,
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 799 | pytype | ref | function | isinstance(elt, nodes.Const) and elt.pytype() in _AST_NODE_STR_TYPES
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 819 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 823 | process_string_token | def | function | def process_string_token(self, token, start_row, start_col):
quote_char = None
index = None
for index, char in enumerate(token):
if char in "'\"":
quote_char = char
break
if quote_char is None:
return
prefix = token[:index].lower() # markers like u, b, r.
after_prefix = token[index:]
# Chop off quotes
quote_length = (
3 if after_prefix[:3] == after_prefix[-3:] == 3 * quote_char else 1
)
string_body = after_prefix[quote_length:-quote_length]
# No special checks on raw strings at the moment.
if "r" not in prefix:
self.process_non_raw_string_token(
prefix,
string_body,
start_row,
start_col + len(prefix) + quote_length,
)
def process_non_raw_string_token(
self, prefix, string_body, start_row, string_start_col
):
"""Check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line number in the source.
string_start_col: integer col number of the string start in the source.
"""
# Walk through the string; if we see a backslash then escape the next
# character, and skip over it. If we see a non-escaped character,
# alert, and continue.
#
# Accept a backslash when it escapes a backslash, or a quote, or
# end-of-line, or one of the letters that introduce a special escape
# sequence <https://docs.python.org/reference/lexical_analysis.html>
#
index = 0
while _True:
index = string_body.find("\\", index)
if index == -1:
break
# There must be a next character; having a backslash at the end
# of the string would be a SyntaxError.
next_char = string_body[index + 1]
match = string_body[index : index + 2]
# The column offset will vary depending on whether the string token
# is broken across lines. Calculate relative to the nearest line
# break or relative to the start of the token's line.
last_newline = string_body.rfind("\n", 0, index)
if last_newline == -1:
line = start_row
col_offset = index + string_start_col
else:
line = start_row + string_body.count("\n", 0, index)
col_offset = index - last_newline - 1
if next_char in self.UNICODE_ESCAPE_CHARACTERS:
if "u" in prefix:
pass
elif "b" not in prefix:
pass # unicode by default
else:
self.add_message(
"anomalous-unicode-escape-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
elif next_char not in self.ESCAPE_CHARACTERS:
self.add_message(
"anomalous-backslash-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
# Whether it was a valid escape or not, backslash followed by
# another character can always be consumed whole: the second
# character can never be the start of a new backslash escape.
index += 2
@check_messages("redundant-u-string-prefix")
def visit_const(self, node: nodes.Const) -> None:
if node.pytype() == "builtins.str" and not isinstance(
node.parent, nodes.JoinedStr
):
self._detect_u_string_prefix(node)
def _detect_u_string_prefix(self, node: nodes.Const):
"""Check whether strings include a 'u' prefix like u'String'."""
if node.kind == "u":
self.add_message(
"redundant-u-string-prefix",
line=node.lineno,
col_offset=node.col_offset,
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 842 | process_non_raw_string_token | ref | function | self.process_non_raw_string_token(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 849 | process_non_raw_string_token | def | function | def process_non_raw_string_token(
self, prefix, string_body, start_row, string_start_col
):
"""Check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line number in the source.
string_start_col: integer col number of the string start in the source.
"""
# Walk through the string; if we see a backslash then escape the next
# character, and skip over it. If we see a non-escaped character,
# alert, and continue.
#
# Accept a backslash when it escapes a backslash, or a quote, or
# end-of-line, or one of the letters that introduce a special escape
# sequence <https://docs.python.org/reference/lexical_analysis.html>
#
index = 0
while _True:
index = string_body.find("\\", index)
if index == -1:
break
# There must be a next character; having a backslash at the end
# of the string would be a SyntaxError.
next_char = string_body[index + 1]
match = string_body[index : index + 2]
# The column offset will vary depending on whether the string token
# is broken across lines. Calculate relative to the nearest line
# break or relative to the start of the token's line.
last_newline = string_body.rfind("\n", 0, index)
if last_newline == -1:
line = start_row
col_offset = index + string_start_col
else:
line = start_row + string_body.count("\n", 0, index)
col_offset = index - last_newline - 1
if next_char in self.UNICODE_ESCAPE_CHARACTERS:
if "u" in prefix:
pass
elif "b" not in prefix:
pass # unicode by default
else:
self.add_message(
"anomalous-unicode-escape-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
elif next_char not in self.ESCAPE_CHARACTERS:
self.add_message(
"anomalous-backslash-in-string",
line=line,
args=(match,),
col_offset=col_offset,
)
# Whether it was a valid escape or not, backslash followed by
# another character can always be consumed whole: the second
# character can never be the start of a new backslash escape.
index += 2
@check_messages("redundant-u-string-prefix")
def visit_const(self, node: nodes.Const) -> None:
if node.pytype() == "builtins.str" and not isinstance(
node.parent, nodes.JoinedStr
):
self._detect_u_string_prefix(node)
def _detect_u_string_prefix(self, node: nodes.Const):
"""Check whether strings include a 'u' prefix like u'String'."""
if node.kind == "u":
self.add_message(
"redundant-u-string-prefix",
line=node.lineno,
col_offset=node.col_offset,
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 893 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 900 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 911 | check_messages | ref | function | @check_messages("redundant-u-string-prefix")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 912 | visit_const | def | function | def visit_const(self, node: nodes.Const) -> None:
if node.pytype() == "builtins.str" and not isinstance(
node.parent, nodes.JoinedStr
):
self._detect_u_string_prefix(node)
def _detect_u_string_prefix(self, node: nodes.Const):
"""Check whether strings include a 'u' prefix like u'String'."""
if node.kind == "u":
self.add_message(
"redundant-u-string-prefix",
line=node.lineno,
col_offset=node.col_offset,
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 913 | pytype | ref | function | if node.pytype() == "builtins.str" and not isinstance(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 916 | _detect_u_string_prefix | ref | function | self._detect_u_string_prefix(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 918 | _detect_u_string_prefix | def | function | def _detect_u_string_prefix(self, node: nodes.Const):
"""Check whether strings include a 'u' prefix like u'String'."""
if node.kind == "u":
self.add_message(
"redundant-u-string-prefix",
line=node.lineno,
col_offset=node.col_offset,
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 921 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 928 | register | def | function | def register(linter: "PyLinter") -> None:
linter.register_checker(StringFormatChecker(linter))
linter.register_checker(StringConstantChecker(linter))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 929 | register_checker | ref | function | linter.register_checker(StringFormatChecker(linter))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 929 | StringFormatChecker | ref | function | linter.register_checker(StringFormatChecker(linter))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 930 | register_checker | ref | function | linter.register_checker(StringConstantChecker(linter))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 930 | StringConstantChecker | ref | function | linter.register_checker(StringConstantChecker(linter))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 933 | str_eval | def | function | def str_eval(token):
"""Mostly replicate `ast.literal_eval(token)` manually to avoid any performance hit.
This supports f-strings, contrary to `ast.literal_eval`.
We have to support all string literal notations:
https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
"""
if token[0:2].lower() in {"fr", "rf"}:
token = token[2:]
elif token[0].lower() in {"r", "u", "f"}:
token = token[1:]
if token[0:3] in {'"""', "'''"}:
return token[3:-3]
return token[1:-1]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 948 | _is_long_string | def | function | def _is_long_string(string_token: str) -> bool:
"""Is this string token a "longstring" (is it triple-quoted)?
Long strings are triple-quoted as defined in
https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
This function only checks characters up through the open quotes. Because it's meant
to be applied only to tokens that represent string literals, it doesn't bother to
check for close-quotes (demonstrating that the literal is a well-formed string).
Args:
string_token: The string token to be parsed.
Returns:
A boolean representing whether this token matches a longstring
regex.
"""
return bool(
SINGLE_QUOTED_REGEX.match(string_token)
or DOUBLE_QUOTED_REGEX.match(string_token)
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 971 | _get_quote_delimiter | def | function | def _get_quote_delimiter(string_token: str) -> str:
"""Returns the quote character used to delimit this token string.
This function checks whether the token is a well-formed string.
Args:
string_token: The token to be parsed.
Returns:
A string containing solely the first quote delimiter character in the
given string.
Raises:
ValueError: No quote delimiter characters are present.
"""
match = QUOTE_DELIMITER_REGEX.match(string_token)
if not match:
raise ValueError(f"string token {string_token} is not a well-formed string")
return match.group(2)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 992 | _is_quote_delimiter_chosen_freely | def | function | def _is_quote_delimiter_chosen_freely(string_token: str) -> bool:
"""Was there a non-awkward option for the quote delimiter?
Args:
string_token: The quoted string whose delimiters are to be checked.
Returns:
Whether there was a choice in this token's quote character that would
not have involved backslash-escaping an interior quote character. Long
strings are excepted from this analysis under the assumption that their
quote characters are set by policy.
"""
quote_delimiter = _get_quote_delimiter(string_token)
unchosen_delimiter = '"' if quote_delimiter == "'" else "'"
return bool(
quote_delimiter
and not _is_long_string(string_token)
and unchosen_delimiter not in str_eval(string_token)
)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 1,004 | _get_quote_delimiter | ref | function | quote_delimiter = _get_quote_delimiter(string_token)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 1,008 | _is_long_string | ref | function | and not _is_long_string(string_token)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/strings.py | pylint/checkers/strings.py | 1,009 | str_eval | ref | function | and unchosen_delimiter not in str_eval(string_token)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/threading_checker.py | pylint/checkers/threading_checker.py | 15 | ThreadingChecker | def | class | visit_with |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/threading_checker.py | pylint/checkers/threading_checker.py | 43 | check_messages | ref | function | @check_messages("useless-with-lock")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/threading_checker.py | pylint/checkers/threading_checker.py | 44 | visit_with | def | function | def visit_with(self, node: nodes.With) -> None:
context_managers = (c for c, _ in node.items if isinstance(c, nodes.Call))
for context_manager in context_managers:
if isinstance(context_manager, nodes.Call):
infered_function = safe_infer(context_manager.func)
if infered_function is None:
continue
qname = infered_function.qname()
if qname in self.LOCKS:
self.add_message("useless-with-lock", node=node, args=qname)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.