Skip to content

Commit 134b784

Browse files
[DuckDBPyType] Add __hash__ method overload (duckdb#61)
This PR fixes https://github.com/duckdb/duckdb/issues/19018#issuecomment-3299362636
2 parents 7a70392 + f3ab971 commit 134b784

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

src/duckdb_py/typing/pytype.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,9 @@ void DuckDBPyType::Initialize(py::handle &m) {
330330
py::is_operator());
331331
type_module.def("__eq__", &DuckDBPyType::EqualsString, "Compare two types for equality", py::arg("other"),
332332
py::is_operator());
333+
type_module.def("__hash__", [](const DuckDBPyType &type) {
334+
return py::hash(py::str(type.ToString()));
335+
});
333336
type_module.def_property_readonly("id", &DuckDBPyType::GetId);
334337
type_module.def_property_readonly("children", &DuckDBPyType::Children);
335338
type_module.def(py::init<>([](const string &type_str, shared_ptr<DuckDBPyConnection> connection = nullptr) {

tests/fast/test_type.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,20 @@ def test_struct_from_dict(self):
214214
res = duckdb.list_type({'a': VARCHAR, 'b': VARCHAR})
215215
assert res == 'STRUCT(a VARCHAR, b VARCHAR)[]'
216216

217+
def test_hash_method(self):
218+
type1 = duckdb.list_type({'a': VARCHAR, 'b': VARCHAR})
219+
type2 = duckdb.list_type({'b': VARCHAR, 'a': VARCHAR})
220+
type3 = VARCHAR
221+
222+
type_set = set()
223+
type_set.add(type1)
224+
type_set.add(type2)
225+
type_set.add(type3)
226+
227+
type_set.add(type1)
228+
expected = ['STRUCT(a VARCHAR, b VARCHAR)[]', 'STRUCT(b VARCHAR, a VARCHAR)[]', 'VARCHAR']
229+
assert sorted([str(x) for x in list(type_set)]) == expected
230+
217231
# NOTE: we can support this, but I don't think going through hoops for an outdated version of python is worth it
218232
@pytest.mark.skipif(sys.version_info < (3, 9), reason="python3.7 does not store Optional[..] in a recognized way")
219233
def test_optional(self):

0 commit comments

Comments
 (0)