Skip to content

Feature request: warn on set creation with unhashable types #21349

@gtkacz

Description

@gtkacz

Summary

If an user is trying to create a set or similar on unhashable types, it will error with something like TypeError: unhashable type: 'list'. This can easily be warned by ruff if it knows the type of the variable by checking for the existence of the __hash__ method.

Which would warn the user in something like:

some_set = set([{'foo': 'bar'}])

Worth pointing out that iterables with root-level hashable types can be passed, e.g.:

set({'foo': 'bar'})
>>> {'foo'}

set([0, 1, 2])
>>> {0, 1, 2}

Example checker implementation in Python:

def is_unhashable(var: Any) -> bool:
	if not var.__class__.__hash__ and (var.__class__.__iter__ and not var[0].__class__.__hash__):
		return True

	return False

is_unhashable([0, 1, 2])
>>> False

is_unhashable([{'foo': 'bar'}])
>>> True

is_unhashable('foo')
>>> False

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs-decisionAwaiting a decision from a maintainerruleImplementing or modifying a lint rule

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions