From f7ab9a6e7c8d91a8179627d84478ee5a9888e8ed Mon Sep 17 00:00:00 2001 From: Kodi Arfer Date: Thu, 2 Nov 2017 13:35:52 -0700 Subject: [PATCH] Make hy-repr support dictionary views --- hy/contrib/hy_repr.hy | 23 +++++++++++++++++------ tests/native_tests/contrib/hy_repr.hy | 5 +++++ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/hy/contrib/hy_repr.hy b/hy/contrib/hy_repr.hy index 669c486..8d67522 100644 --- a/hy/contrib/hy_repr.hy +++ b/hy/contrib/hy_repr.hy @@ -7,6 +7,12 @@ [hy._compat [PY3 str-type bytes-type long-type]] [hy.models [HyObject HyExpression HySymbol HyKeyword HyInteger HyFloat HyComplex HyList HyDict HySet HyString HyBytes]]) +(try + (import [_collections_abc [dict-keys dict-values dict-items]]) + (except [ImportError] + (defclass C) + (setv [dict-keys dict-values dict-items] [C C C]))) + (setv -registry {}) (defn hy-repr-register [types f &optional placeholder] (for [typ (if (instance? list types) types [types])] @@ -39,8 +45,6 @@ (when started-quoting (setv -quoting False))))) -(hy-repr-register list :placeholder "[...]" (fn [x] - (+ "[" (-cat x) "]"))) (hy-repr-register tuple (fn [x] (+ "(," (if x " " "") (-cat x) ")"))) (hy-repr-register dict :placeholder "{...}" (fn [x] @@ -55,10 +59,6 @@ (if (% (len x) 2) (+= text (+ " " (hy-repr (get x -1))))) (+ "{" text "}"))) -(hy-repr-register [set HySet] (fn [x] - (+ "#{" (-cat x) "}"))) -(hy-repr-register frozenset (fn [x] - (+ "(frozenset #{" (-cat x) "})"))) (hy-repr-register HyExpression (fn [x] (setv syntax { 'quote "'" @@ -101,6 +101,17 @@ (hy-repr-register fraction (fn [x] (.format "{}/{}" (hy-repr x.numerator) (hy-repr x.denominator)))) +(for [[types fmt] (partition [ + list "[...]" + [set HySet] "#{...}" + frozenset "(frozenset #{...})" + dict-keys "(dict-keys [...])" + dict-values "(dict-values [...])" + dict-items "(dict-items [...])"])] + (defn mkrepr [fmt] + (fn [x] (.replace fmt "..." (-cat x) 1))) + (hy-repr-register types :placeholder fmt (mkrepr fmt))) + (defn -cat [obj] (.join " " (map hy-repr obj))) diff --git a/tests/native_tests/contrib/hy_repr.hy b/tests/native_tests/contrib/hy_repr.hy index 9821c90..076c16b 100644 --- a/tests/native_tests/contrib/hy_repr.hy +++ b/tests/native_tests/contrib/hy_repr.hy @@ -87,6 +87,11 @@ (assert (= (hy-repr (str ':mykeyword)) ":mykeyword")) (assert (= (hy-repr (.encode kw "UTF-8") #[[b"\xef\xb7\x90:hello"]]))))) +(when PY3 (defn test-dict-views [] + (assert (= (hy-repr (.keys {1 2})) "(dict-keys [1])")) + (assert (= (hy-repr (.values {1 2})) "(dict-values [2])")) + (assert (= (hy-repr (.items {1 2})) "(dict-items [(, 1 2)])")))) + (defn test-hy-model-constructors [] (import hy) (assert (= (hy-repr (hy.HyInteger 7)) "'7"))