Skip to content

Commit 59a5be1

Browse files
committed
Fix float ctor with subclassed PInt should call __float__
1 parent 03696df commit 59a5be1

File tree

2 files changed

+16
-9
lines changed

2 files changed

+16
-9
lines changed

graalpython/com.oracle.graal.python.test/src/tests/test_formatting.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,14 @@ def test_formatting():
8888
assert format(1234.5, "+n").startswith("+")
8989

9090

91+
def test_int_format():
92+
class PolymorphInt(int):
93+
def __float__(self):
94+
return 42.5
95+
96+
assert format(PolymorphInt(2), "g") == '42.5'
97+
98+
9199
class MyComplex(complex):
92100
def __repr__(self):
93101
return 'wrong answer'

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/BuiltinConstructors.java

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -957,8 +957,9 @@ Object floatFromLong(Object cls, long arg) {
957957
return factory().createFloat(cls, arg);
958958
}
959959

960-
@Specialization(guards = "!isNativeClass(cls)")
961-
Object floatFromPInt(Object cls, PInt arg) {
960+
@Specialization(guards = {"!isNativeClass(cls)", "cannotBeOverridden(plib.getLazyPythonClass(arg))"})
961+
Object floatFromPInt(Object cls, PInt arg,
962+
@CachedLibrary(limit = "1") @SuppressWarnings("unused") PythonObjectLibrary plib) {
962963
double value = arg.doubleValue();
963964
if (Double.isInfinite(value)) {
964965
throw raise(OverflowError, ErrorMessages.TOO_LARGE_TO_CONVERT_TO, "int", "float");
@@ -1096,11 +1097,14 @@ Object floatFromNone(Object cls, @SuppressWarnings("unused") PNone arg) {
10961097
return factory().createFloat(cls, 0.0);
10971098
}
10981099

1099-
static boolean isHandledType(Object o) {
1100+
static boolean isHandledType(PythonObjectLibrary lib, Object o) {
1101+
if (o instanceof PInt) {
1102+
return PGuards.cannotBeOverridden(lib.getLazyPythonClass(o));
1103+
}
11001104
return PGuards.canBeInteger(o) || PGuards.isDouble(o) || o instanceof String || PGuards.isPNone(o);
11011105
}
11021106

1103-
@Specialization(guards = {"isPrimitiveFloat(cls)", "!isHandledType(obj)"})
1107+
@Specialization(guards = {"isPrimitiveFloat(cls)", "!isHandledType(lib, obj)"})
11041108
double doubleFromObject(VirtualFrame frame, @SuppressWarnings("unused") Object cls, Object obj,
11051109
@CachedLibrary(limit = "1") PythonObjectLibrary lib) {
11061110
// Follows logic from PyNumber_Float:
@@ -3181,11 +3185,6 @@ private String getStringArg(Object arg) {
31813185
throw raise(SystemError, ErrorMessages.BAD_ARG_TO_INTERNAL_FUNC);
31823186
}
31833187
}
3184-
3185-
@TruffleBoundary
3186-
private static byte[] toBytes(String data) {
3187-
return data.getBytes();
3188-
}
31893188
}
31903189

31913190
@Builtin(name = "cell", constructsClass = PythonBuiltinClassType.PCell, isPublic = false)

0 commit comments

Comments
 (0)