Skip to content

Commit 0644809

Browse files
authored
accept integer-valued numbers for Integer (#919)
allows config to cast e.g. the float 4e9 to int without error if the value is unchanged
1 parent 945250c commit 0644809

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

tests/test_traitlets.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
# also under the terms of the Modified BSD License.
88
from __future__ import annotations
99

10+
import decimal
1011
import pickle
1112
import re
1213
import typing as t
@@ -1391,7 +1392,7 @@ class TestLong(TraitTestBase):
13911392
obj = LongTrait()
13921393

13931394
_default_value = 99
1394-
_good_values = [10, -10]
1395+
_good_values = [10, -10, 10.0, decimal.Decimal("10.0")]
13951396
_bad_values = [
13961397
"ten",
13971398
[10],
@@ -1401,6 +1402,7 @@ class TestLong(TraitTestBase):
14011402
1j,
14021403
10.1,
14031404
-10.1,
1405+
decimal.Decimal("10.1"),
14041406
"10",
14051407
"-10",
14061408
"10L",

traitlets/traitlets.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
import contextlib
4545
import enum
4646
import inspect
47+
import numbers
4748
import os
4849
import re
4950
import sys
@@ -2635,6 +2636,15 @@ def __init__(
26352636
)
26362637

26372638
def validate(self, obj: t.Any, value: t.Any) -> G:
2639+
if not isinstance(value, int) and isinstance(value, numbers.Number):
2640+
# allow casting integer-valued numbers to int
2641+
# allows for more concise assignment like `4e9` which is a float
2642+
try:
2643+
int_value = int(value)
2644+
if int_value == value:
2645+
value = int_value
2646+
except Exception:
2647+
pass
26382648
if not isinstance(value, int):
26392649
self.error(obj, value)
26402650
return _validate_bounds(self, obj, value) # type:ignore[no-any-return]

0 commit comments

Comments
 (0)