Skip to content

Commit b61b454

Browse files
committed
builtin: Implement builtin_ascii
Implement builtin ascii
1 parent c5b8c68 commit b61b454

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

builtin/builtin.go

+34-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
package builtin
77

88
import (
9+
"strconv"
10+
"strings"
11+
"unicode"
912
"unicode/utf8"
1013

1114
"github.com/go-python/gpython/compile"
@@ -24,7 +27,7 @@ func init() {
2427
py.MustNewMethod("abs", builtin_abs, 0, abs_doc),
2528
py.MustNewMethod("all", builtin_all, 0, all_doc),
2629
py.MustNewMethod("any", builtin_any, 0, any_doc),
27-
// py.MustNewMethod("ascii", builtin_ascii, 0, ascii_doc),
30+
py.MustNewMethod("ascii", builtin_ascii, 0, ascii_doc),
2831
// py.MustNewMethod("bin", builtin_bin, 0, bin_doc),
2932
// py.MustNewMethod("callable", builtin_callable, 0, callable_doc),
3033
py.MustNewMethod("chr", builtin_chr, 0, chr_doc),
@@ -309,6 +312,36 @@ func builtin_any(self, seq py.Object) (py.Object, error) {
309312
return py.False, nil
310313
}
311314

315+
const ascii_doc = `ascii(obj, /)
316+
Return an ASCII-only representation of an object.
317+
318+
As repr(), return a string containing a printable representation of an
319+
object, but escape the non-ASCII characters in the string returned by
320+
repr() using \\x, \\u or \\U escapes. This generates a string similar
321+
to that returned by repr() in Python 2
322+
`
323+
324+
func builtin_ascii(self, o py.Object) (py.Object, error) {
325+
reprObject, err := py.Repr(o)
326+
if err != nil {
327+
return nil, err
328+
}
329+
330+
var sb strings.Builder
331+
repr := reprObject.(py.String)
332+
for _, c := range repr {
333+
if c <= unicode.MaxASCII {
334+
sb.WriteRune(c)
335+
} else {
336+
s := "\\u" + strconv.FormatInt(int64(c), 16)
337+
sb.WriteString(s)
338+
}
339+
}
340+
341+
ascii := sb.String()
342+
return py.String(ascii), nil
343+
}
344+
312345
const round_doc = `round(number[, ndigits]) -> number
313346
314347
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)