Skip to content

Commit bffb0f4

Browse files
committed
Implement int()
1 parent 1e659f3 commit bffb0f4

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

py/int.go

+45-1
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,24 @@ package py
55
import (
66
"math"
77
"math/big"
8+
"strconv"
89
)
910

10-
var IntType = NewType("int", "int(x=0) -> integer\nint(x, base=10) -> integer\n\nConvert a number or string to an integer, or return 0 if no arguments\nare given. If x is a number, return x.__int__(). For floating point\nnumbers, this truncates towards zero.\n\nIf x is not a number or if base is given, then x must be a string,\nbytes, or bytearray instance representing an integer literal in the\ngiven base. The literal can be preceded by '+' or '-' and be surrounded\nby whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\nBase 0 means to interpret the base from the string as an integer literal.\n>>> int('0b100', base=0)\n4")
11+
var IntType = ObjectType.NewType("int", `
12+
int(x=0) -> integer
13+
int(x, base=10) -> integer
14+
15+
Convert a number or string to an integer, or return 0 if no arguments
16+
are given. If x is a number, return x.__int__(). For floating point
17+
numbers, this truncates towards zero.
18+
19+
If x is not a number or if base is given, then x must be a string,
20+
bytes, or bytearray instance representing an integer literal in the
21+
given base. The literal can be preceded by '+' or '-' and be surrounded
22+
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
23+
Base 0 means to interpret the base from the string as an integer literal.
24+
>>> int('0b100', base=0)
25+
4`, IntNew, nil)
1126

1227
type Int int64
1328

@@ -35,6 +50,35 @@ func (o *BigInt) Type() *Type {
3550
// Make sure it satisfies the interface
3651
var _ Object = (*BigInt)(nil)
3752

53+
// IntNew
54+
func IntNew(metatype *Type, args Tuple, kwargs StringDict) Object {
55+
var xObj Object = Int(0)
56+
var baseObj Object = Int(10)
57+
ParseTupleAndKeywords(args, kwargs, "|OO:int", []string{"x", "base"}, &xObj, &baseObj)
58+
var res Int
59+
switch x := xObj.(type) {
60+
case Int:
61+
res = x
62+
case String:
63+
base := int(baseObj.(Int))
64+
// FIXME this isn't 100% python compatible but it is close!
65+
i, err := strconv.ParseInt(string(x), base, 64)
66+
if err != nil {
67+
panic(ExceptionNewf(ValueError, "invalid literal for int() with base %d: '%s'", base, string(x)))
68+
}
69+
res = Int(i)
70+
case Float:
71+
res = Int(x)
72+
default:
73+
var ok bool
74+
res, ok = convertToInt(x)
75+
if !ok {
76+
panic(ExceptionNewf(TypeError, "int() argument must be a string or a number, not 'tuple'"))
77+
}
78+
}
79+
return res
80+
}
81+
3882
// Arithmetic
3983

4084
// Convert an Object to an Int

0 commit comments

Comments
 (0)