Skip to content

Commit 67806f7

Browse files
authored
Add format and printf string format functions (#401)
* Add format and printf string format functions * Macro correctly
1 parent 323527f commit 67806f7

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

src/basilisp/core.lpy

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1862,6 +1862,22 @@
18621862
~@(next forms))
18631863
x))
18641864

1865+
;;;;;;;;;;;;;;;;;;;;;;
1866+
;; String Functions ;;
1867+
;;;;;;;;;;;;;;;;;;;;;;
1868+
1869+
(import* os)
1870+
1871+
(defn format
1872+
"Format a string as by Python's `%` operator."
1873+
[fmt & args]
1874+
(if (= 1 (count args))
1875+
(let [arg (first args)]
1876+
(if (or (map? arg) (py-dict? arg))
1877+
(operator/mod fmt (python/dict arg))
1878+
(operator/mod fmt arg)))
1879+
(operator/mod fmt (python/tuple args))))
1880+
18651881
;;;;;;;;;;;;;;;;;;;;;;
18661882
;; Output Utilities ;;
18671883
;;;;;;;;;;;;;;;;;;;;;;
@@ -1882,6 +1898,19 @@
18821898
[]
18831899
(.flush *out*))
18841900

1901+
(defn newline
1902+
"Write a platform specific newline to *out*."
1903+
[]
1904+
(.write *out* os/linesep)
1905+
nil)
1906+
1907+
(defmacro with-in-str
1908+
"Evaluate body with *in* bound to a io.StringIO instance containing the
1909+
string s."
1910+
[s & body]
1911+
`(binding [*in* (io/StringIO ~s)]
1912+
~@body))
1913+
18851914
(defmacro with-out-str
18861915
"Capture the contents of text sent to *out* and return the contents as a
18871916
string."
@@ -1991,6 +2020,13 @@
19912020
(with-out-str
19922021
(apply println args)))
19932022

2023+
(defn printf
2024+
"Prints formatted output as per format.
2025+
2026+
Does not append a newline."
2027+
[fmt & args]
2028+
(print (apply format fmt args)))
2029+
19942030
;;;;;;;;;;;;;;;;;;;;
19952031
;; REPL Utilities ;;
19962032
;;;;;;;;;;;;;;;;;;;;
@@ -2805,7 +2841,7 @@
28052841

28062842
(import* abc)
28072843

2808-
(defmulti ^:private munge
2844+
(defmulti munge
28092845
"Munge the input value into a Python-safe string. Converts keywords and
28102846
symbols into strings as by `name` prior to munging. Returns a string."
28112847
python/type)
@@ -2822,6 +2858,10 @@
28222858
[s]
28232859
(basilisp.lang.util/munge s))
28242860

2861+
(def namespace-munge
2862+
"Convert a Basilisp namespace name to a valid Python name."
2863+
munge)
2864+
28252865
(defn gen-interface
28262866
"Generate and return a new Python interface (abstract base clase).
28272867

0 commit comments

Comments
 (0)