How to use is_len_call method in refurb

Best Python code snippet using refurb_python

subscripts.py

Source: subscripts.py Github

copy

Full Screen

1import ast2from typing_extensions import final3from wemake_python_styleguide.logic import source4from wemake_python_styleguide.logic.tree import functions, operators, slices5from wemake_python_styleguide.violations import (6 best_practices,7 consistency,8 refactoring,9)10from wemake_python_styleguide.visitors import base11@final12class SubscriptVisitor(base.BaseNodeVisitor):13 """Checks subscripts used in the code."""14 def visit_Subscript(self, node: ast.Subscript) -> None:15 """16 Visits subscript.17 Raises:18 RedundantSubscriptViolation19 """20 self._check_redundant_subscript(node)21 self.generic_visit(node)22 def _check_redundant_subscript(self, node: ast.Subscript) -> None:23 if not isinstance(node.slice, ast.Slice):24 return25 lower_ok = (26 node.slice.lower is None or (27 not self._is_zero(node.slice.lower) and28 not self._is_none(node.slice.lower)29 )30 )31 upper_ok = (32 node.slice.upper is None or33 not self._is_none(node.slice.upper)34 )35 step_ok = (36 node.slice.step is None or (37 not self._is_one(node.slice.step) and38 not self._is_none(node.slice.step)39 )40 )41 if not (lower_ok and upper_ok and step_ok):42 self.add_violation(43 consistency.RedundantSubscriptViolation(44 node, text=str(node),45 ),46 )47 def _is_none(self, component_value: ast.expr) -> bool:48 return (49 isinstance(component_value, ast.NameConstant) and50 component_value.value is None51 )52 def _is_zero(self, component_value: ast.expr) -> bool:53 return isinstance(component_value, ast.Num) and component_value.n == 054 def _is_one(self, component_value: ast.expr) -> bool:55 return isinstance(component_value, ast.Num) and component_value.n == 156@final57class ImplicitDictGetVisitor(base.BaseNodeVisitor):58 """Checks for correct ``.get`` usage in code."""59 def visit_If(self, node: ast.If) -> None:60 """61 Checks the compares.62 Raises:63 ImplicitDictGetViolation64 """65 self._check_implicit_get(node)66 self.generic_visit(node)67 def _check_implicit_get(self, node: ast.If) -> None:68 if not isinstance(node.test, ast.Compare):69 return70 if not isinstance(node.test.ops[0], ast.In):71 return72 checked_key = source.node_to_string(node.test.left)73 checked_collection = source.node_to_string(node.test.comparators[0])74 for sub in ast.walk(node):75 if not isinstance(sub, ast.Subscript):76 continue77 if slices.is_same_slice(checked_collection, checked_key, sub):78 self.add_violation(refactoring.ImplicitDictGetViolation(sub))79@final80class CorrectKeyVisitor(base.BaseNodeVisitor):81 """Checks for correct keys usage in your code."""82 def visit_Subscript(self, node: ast.Subscript) -> None:83 """84 Checks that key usage is correct, without any errors.85 Raises:86 FloatKeyViolation87 ImplicitNegativeIndexViolation88 """89 self._check_float_key(node)90 self._check_len_call(node)91 self.generic_visit(node)92 def _check_float_key(self, node: ast.Subscript) -> None:93 is_float_key = (94 isinstance(node.slice, ast.Index) and95 self._is_float_key(node.slice)96 )97 if is_float_key:98 self.add_violation(best_practices.FloatKeyViolation(node))99 def _check_len_call(self, node: ast.Subscript) -> None:100 is_len_call = (101 isinstance(node.slice, ast.Index) and102 isinstance(node.slice.value, ast.BinOp) and103 isinstance(node.slice.value.op, ast.Sub) and104 self._is_wrong_len(105 node.slice.value,106 source.node_to_string(node.value),107 )108 )109 if is_len_call:110 self.add_violation(111 refactoring.ImplicitNegativeIndexViolation(node),112 )113 def _is_wrong_len(self, node: ast.BinOp, element: str) -> bool:114 return (115 isinstance(node.left, ast.Call) and116 bool(functions.given_function_called(node.left, {'len'})) and117 source.node_to_string(node.left.args[0]) == element118 )119 def _is_float_key(self, node: ast.Index) -> bool:120 real_node = operators.unwrap_unary_node(node.value)121 return (122 isinstance(real_node, ast.Num) and123 isinstance(real_node.n, float)...

Full Screen

Full Screen

no_len_cmp.py

Source: no_len_cmp.py Github

copy

Full Screen

...70 return True71 case DictExpr() | ListExpr() | StrExpr() | TupleExpr():72 return True73 return False74def is_len_call(node: CallExpr) -> bool:75 match node:76 case CallExpr(77 callee=NameExpr(fullname="builtins.len"),78 args=[arg],79 ) if is_builtin_container_like(arg):80 return True81 return False82IS_COMPARISON_TRUTHY: dict[tuple[str, int], bool] = {83 ("==", 0): False,84 ("<=", 0): False,85 (">", 0): True,86 ("!=", 0): True,87 (">=", 1): True,88}89class LenComparisonVisitor(TraverserVisitor):90 errors: list[Error]91 def __init__(self, errors: list[Error]) -> None:92 super().__init__()93 self.errors = errors94 for name, ty in METHOD_NODE_MAPPINGS.items():95 if ty in (ComparisonExpr, UnaryExpr, OpExpr, CallExpr):96 continue97 def inner(self: "LenComparisonVisitor", o: Node) -> None:98 return99 setattr(self, name, inner.__get__(self))100 def visit_comparison_expr(self, node: ComparisonExpr) -> None:101 match node:102 case ComparisonExpr(103 operators=[oper],104 operands=[CallExpr() as call, IntExpr(value=num)],105 ) if is_len_call(call):106 is_truthy = IS_COMPARISON_TRUTHY.get((oper, num))107 if is_truthy is None:108 return109 expr = "x" if is_truthy else "not x"110 self.errors.append(111 ErrorInfo(112 node.line,113 node.column,114 f"Replace `len(x) {oper} {num}` with `{expr}`",115 )116 )117 def visit_call_expr(self, node: CallExpr) -> None:118 if is_len_call(node):119 self.errors.append(120 ErrorInfo(node.line, node.column, "Replace `len(x)` with `x`")121 )122ConditionLikeNode = (123 IfStmt124 | MatchStmt125 | GeneratorExpr126 | DictionaryComprehension127 | ConditionalExpr128 | WhileStmt129 | AssertStmt130)131def check(node: ConditionLikeNode, errors: list[Error]) -> None:132 check_condition_like(LenComparisonVisitor(errors), node)...

Full Screen

Full Screen

Blogs

Check out the latest blogs from LambdaTest on this topic:

Test strategy and how to communicate it

I routinely come across test strategy documents when working with customers. They are lengthy—100 pages or more—and packed with monotonous text that is routinely reused from one project to another. Yawn once more— the test halt and resume circumstances, the defect management procedure, entrance and exit criteria, unnecessary generic risks, and in fact, one often-used model replicates the requirements of textbook testing, from stress to systems integration.

Rebuild Confidence in Your Test Automation

These days, development teams depend heavily on feedback from automated tests to evaluate the quality of the system they are working on.

Developers and Bugs &#8211; why are they happening again and again?

Entering the world of testers, one question started to formulate in my mind: “what is the reason that bugs happen?”.

Six Agile Team Behaviors to Consider

Are members of agile teams different from members of other teams? Both yes and no. Yes, because some of the behaviors we observe in agile teams are more distinct than in non-agile teams. And no, because we are talking about individuals!

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run refurb automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful