diff --git a/README.md b/README.md index 247d9ce31..b468b3ed6 100644 --- a/README.md +++ b/README.md @@ -228,6 +228,7 @@ Uninstall with `nimble uninstall pylib`. - [x] `format()` - [x] `getattr()` - [x] `hasattr()` +- [x] `hash()` - [x] `hex()` - [x] `id()` - [x] `input()` diff --git a/src/pylib/builtins.nim b/src/pylib/builtins.nim index 39890329c..7f56a930d 100644 --- a/src/pylib/builtins.nim +++ b/src/pylib/builtins.nim @@ -3,4 +3,4 @@ import ./private/trans_imp impExp builtins, input, print, mathfunc, complex, misc, oopFuncs, attr, - iters, pyrange, pyslice, list, dict, set + iters, pyrange, pyslice, list, dict, set, pyhashes diff --git a/src/pylib/builtins/pyhashes.nim b/src/pylib/builtins/pyhashes.nim new file mode 100644 index 000000000..141760375 --- /dev/null +++ b/src/pylib/builtins/pyhashes.nim @@ -0,0 +1,28 @@ + +import std/hashes +import ./[ + list, dict, set, + complex +] +import ../pystring/strimpl +import ../pybytes/bytesimpl + +template toInt(h: Hash): int = int(h) +template hashable(typ){.dirty.} = + proc hash*(x: typ): int = toInt hashes.hash(x) + +hashable int +hashable float +hashable PyComplex +hashable PyStr +hashable PyBytes +hashable tuple +hashable proc + +const unhashErr = "TypeError: unhashable type: " +template unhashable(typ){.dirty.} = + proc hash*(x: typ): int{.error: unhashErr & $typ.} + +unhashable PyList +unhashable PyDict +unhashable PySet