66package builtin
77
88import (
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+
312345const round_doc = `round(number[, ndigits]) -> number
313346
314347Round a number to a given precision in decimal digits (default 0 digits).
0 commit comments