From 0574e275b5174579dc1adc449f2fc499bae4b18a Mon Sep 17 00:00:00 2001 From: Kodi Arfer Date: Fri, 3 Nov 2017 11:56:46 -0700 Subject: [PATCH] Make hy-repr support some `collections` classes --- hy/contrib/hy_repr.hy | 19 ++++++++++++++++++- tests/native_tests/contrib/hy_repr.hy | 18 ++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/hy/contrib/hy_repr.hy b/hy/contrib/hy_repr.hy index 929a7b7..627649a 100644 --- a/hy/contrib/hy_repr.hy +++ b/hy/contrib/hy_repr.hy @@ -6,6 +6,7 @@ [math [isnan]] re datetime + collections [hy._compat [PY3 PY36 str-type bytes-type long-type]] [hy.models [HyObject HyExpression HySymbol HyKeyword HyInteger HyFloat HyComplex HyList HyDict HySet HyString HyBytes]]) @@ -48,7 +49,15 @@ (setv -quoting False))))) (hy-repr-register tuple (fn [x] - (+ "(," (if x " " "") (-cat x) ")"))) + (if (hasattr x "_fields") + ; It's a named tuple. (We can't use `instance?` or so because + ; generated named-tuple classes don't actually inherit from + ; collections.namedtuple.) + (.format "({} {})" + (. (type x) __name__) + (.join " " (genexpr (+ ":" k " " (hy-repr v)) [[k v] (zip x._fields x)]))) + ; Otherwise, print it as a regular tuple. + (+ "(," (if x " " "") (-cat x) ")")))) (hy-repr-register dict :placeholder "{...}" (fn [x] (setv text (.join " " (genexpr (+ (hy-repr k) " " (hy-repr v)) @@ -127,6 +136,14 @@ (if (not (none? x.tzinfo)) (+ ":tzinfo " (hy-repr x.tzinfo))) (if (and PY36 (!= x.fold 0)) (+ ":fold " (hy-repr x.fold)))]))))) +(hy-repr-register collections.Counter (fn [x] + (.format "(Counter {})" + (hy-repr (dict x))))) +(hy-repr-register collections.defaultdict (fn [x] + (.format "(defaultdict {} {})" + (hy-repr x.default-factory) + (hy-repr (dict x))))) + (for [[types fmt] (partition [ list "[...]" [set HySet] "#{...}" diff --git a/tests/native_tests/contrib/hy_repr.hy b/tests/native_tests/contrib/hy_repr.hy index 411d5a4..a896013 100644 --- a/tests/native_tests/contrib/hy_repr.hy +++ b/tests/native_tests/contrib/hy_repr.hy @@ -119,6 +119,24 @@ (assert (= (hy-repr (D.time 1 2 3 4567 :fold 1 :tzinfo D.timezone.utc)) "(datetime.time 1 2 3 4567 :tzinfo datetime.timezone.utc :fold 1)")))) +(defn test-collections [] + (import collections) + (assert (= (hy-repr (collections.defaultdict :a 8)) + (if PY3 + "(defaultdict None {\"a\" 8})" + "(defaultdict None {b\"a\" 8})"))) + (assert (= (hy-repr (collections.defaultdict int :a 8)) + (if PY3 + "(defaultdict {\"a\" 8})" + "(defaultdict {b\"a\" 8})"))) + (assert (= (hy-repr (collections.Counter [15 15 15 15])) + (if PY3 + "(Counter {15 4})" + "(Counter {15 (int 4)})"))) + (setv C (collections.namedtuple "Fooey" ["cd" "a_b"])) + (assert (= (hy-repr (C 11 12)) + "(Fooey :cd 11 :a_b 12)"))) + (defn test-hy-model-constructors [] (import hy) (assert (= (hy-repr (hy.HyInteger 7)) "'7"))