Make hy-repr support some collections
classes
This commit is contained in:
parent
38f461890d
commit
0574e275b5
@ -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] "#{...}"
|
||||
|
@ -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 <class 'int'> {\"a\" 8})"
|
||||
"(defaultdict <type 'int'> {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"))
|
||||
|
Loading…
x
Reference in New Issue
Block a user