6
6
package builtin
7
7
8
8
import (
9
+ "strconv"
10
+ "strings"
11
+ "unicode"
9
12
"unicode/utf8"
10
13
11
14
"github.com/go-python/gpython/compile"
@@ -24,7 +27,7 @@ func init() {
24
27
py .MustNewMethod ("abs" , builtin_abs , 0 , abs_doc ),
25
28
py .MustNewMethod ("all" , builtin_all , 0 , all_doc ),
26
29
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 ),
28
31
// py.MustNewMethod("bin", builtin_bin, 0, bin_doc),
29
32
// py.MustNewMethod("callable", builtin_callable, 0, callable_doc),
30
33
py .MustNewMethod ("chr" , builtin_chr , 0 , chr_doc ),
@@ -309,6 +312,36 @@ func builtin_any(self, seq py.Object) (py.Object, error) {
309
312
return py .False , nil
310
313
}
311
314
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
+
312
345
const round_doc = `round(number[, ndigits]) -> number
313
346
314
347
Round a number to a given precision in decimal digits (default 0 digits).
0 commit comments