Skip to content

Commit ed3b676

Browse files
committed
[WIP] builtin: Implement builtin_ascii
1 parent c5b8c68 commit ed3b676

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

builtin/builtin.go

+33-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
package builtin
77

88
import (
9+
"unicode"
910
"unicode/utf8"
1011

1112
"github.com/go-python/gpython/compile"
@@ -24,7 +25,7 @@ func init() {
2425
py.MustNewMethod("abs", builtin_abs, 0, abs_doc),
2526
py.MustNewMethod("all", builtin_all, 0, all_doc),
2627
py.MustNewMethod("any", builtin_any, 0, any_doc),
27-
// py.MustNewMethod("ascii", builtin_ascii, 0, ascii_doc),
28+
py.MustNewMethod("ascii", builtin_ascii, 0, ascii_doc),
2829
// py.MustNewMethod("bin", builtin_bin, 0, bin_doc),
2930
// py.MustNewMethod("callable", builtin_callable, 0, callable_doc),
3031
py.MustNewMethod("chr", builtin_chr, 0, chr_doc),
@@ -309,6 +310,37 @@ func builtin_any(self, seq py.Object) (py.Object, error) {
309310
return py.False, nil
310311
}
311312

313+
const ascii_doc = `ascii(obj, /)
314+
Return an ASCII-only representation of an object.
315+
316+
As repr(), return a string containing a printable representation of an
317+
object, but escape the non-ASCII characters in the string returned by
318+
repr() using \\x, \\u or \\U escapes. This generates a string similar
319+
to that returned by repr() in Python 2
320+
`
321+
322+
func builtin_ascii(self, o py.Object) (py.Object, error) {
323+
reprObject, err := py.Repr(o)
324+
if err != nil {
325+
return nil, err
326+
}
327+
328+
repr := reprObject.(py.String)
329+
asciiOnly := true
330+
for _, c := range repr {
331+
if c > unicode.MaxASCII {
332+
asciiOnly = false
333+
break
334+
}
335+
}
336+
337+
if asciiOnly {
338+
return repr, nil
339+
}
340+
341+
return nil, py.ExceptionNewf(py.NotImplementedError, "")
342+
}
343+
312344
const round_doc = `round(number[, ndigits]) -> number
313345
314346
Round a number to a given precision in decimal digits (default 0 digits).

builtin/tests/builtin.py

+4
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@
1919
assert any(["hello", "world"]) == True
2020
assert any([]) == False
2121

22+
doc="ascii"
23+
assert ascii('hello world') == "'hello world'"
24+
assert ascii('안녕 세상') == "'\\uc548\\ub155 \\uc138\\uc0c1'"
25+
2226
doc="chr"
2327
assert chr(65) == "A"
2428
assert chr(163) == "£"

0 commit comments

Comments
 (0)