autoflake icon indicating copy to clipboard operation
autoflake copied to clipboard

TypeError: unhashable type errors in filter_unused_variable

Open gabe-sherman opened this issue 1 year ago • 2 comments

The below code triggers an unhashable type error when calling filter_unused_variable. This occurs in 'is_literal_or_name' at line 788 in autoflake.py.

import autoflake
autoflake.filter_unused_variable("g={{}}") # TypeError: unhashable type: 'dict'
autoflake.filter_unused_variable("g={[\n]}") # TypeError: unhashable type: 'list'

Setup Info

Version: 2.31 Commit: b87ff10c51f010a9de33f4cce54564cf232a75be

Trace Report For Each Input

Traceback (most recent call last):
  File "rep.py", line 4, in <module>
    autoflake.filter_unused_variable("g={[\n]}")
  File "python3.10/site-packages/autoflake.py", line 731, in filter_unused_variable
    if is_literal_or_name(value):
  File "python3.10/site-packages/autoflake.py", line 788, in is_literal_or_name
    ast.literal_eval(value)
  File "python3.10/ast.py", line 110, in literal_eval
    return _convert(node_or_string)
  File "python3.10/ast.py", line 92, in _convert
    return set(map(_convert, node.elts))
TypeError: unhashable type: 'dict'
Traceback (most recent call last):
  File "rep.py", line 4, in <module>
    autoflake.filter_unused_variable("g={[\n]}")
  File "python3.10/site-packages/autoflake.py", line 731, in filter_unused_variable
    if is_literal_or_name(value):
  File "python3.10/site-packages/autoflake.py", line 788, in is_literal_or_name
    ast.literal_eval(value)
  File "python3.10/ast.py", line 110, in literal_eval
    return _convert(node_or_string)
  File "python3.10/ast.py", line 92, in _convert
    return set(map(_convert, node.elts))
TypeError: unhashable type: 'list'

gabe-sherman avatar Apr 25 '25 17:04 gabe-sherman

@gabe-sherman autoflake is trying to parse the code and you're calling that function with invalid Python code. How would you prefer to have that error surfaced?

fsouza avatar May 08 '25 17:05 fsouza

Yes I see where you're coming from, but this exception may not be descriptive to the user as to why it's failing. I see that in the function is_literal_or_name, the call to literal_eval is wrapped in a try catch block that ignores SyntaxError and ValueError. Would adding an exception like this to those checks be beneficial for the user?

gabe-sherman avatar May 08 '25 18:05 gabe-sherman