Skip to content
Snippets Groups Projects
Commit 5d21b200 authored by Bryce Guinta's avatar Bryce Guinta
Browse files

Fix len builtin for instances of str or bytes

A ClassDef of str or bytes may have the same qname as a Const value of str or bytes
causing an AttributeError in len builtin inference
parent 3c1731b8
No related branches found
No related tags found
No related merge requests found
Loading
Loading
@@ -240,7 +240,8 @@ def object_len(node, context=None):
inferred_node = safe_infer(node, context=context)
if inferred_node is None or inferred_node is util.Uninferable:
raise exceptions.InferenceError(node=node)
if inferred_node.qname() in ('builtins.str', 'builtins.bytes'):
if (isinstance(inferred_node, nodes.Const) and
isinstance(inferred_node.value, (bytes, str))):
return len(inferred_node.value)
if isinstance(inferred_node, (nodes.List, nodes.Set, nodes.Tuple, FrozenSet)):
return len(inferred_node.elts)
Loading
Loading
Loading
Loading
@@ -1230,6 +1230,17 @@ class TestLenBuiltinInference:
""")
assert next(node.infer()).as_string() == '5'
 
def test_len_builtin_inference_attribute_error_str(self):
"""Make sure len builtin doesn't raise an AttributeError
on instances of str or bytes
See https://github.com/PyCQA/pylint/issues/1942
"""
code = 'len(str("F"))'
try:
next(astroid.extract_node(code).infer())
except astroid.InferenceError:
pass
 
if __name__ == '__main__':
unittest.main()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment