traitlets
traitlets copied to clipboard
Add CInteger trait type
I think there is a need for a CInteger trait: A trait that converts anything you throw at it into a python integer if possible, without enforcing either int
or long
on python 2. In essence, it should simply call int(value)
for coercion, which under python 2 only produces a long
where needed. A typical situation is when numpy array scalars are assigned to a trait, which will be rejected by the non-coercing traits.
I think coercing traits are rarely actually desirable, and we've slowly been removing their use throughout IPython.
For instance, if you have an integer trait, and you do:
hastraits.int_trait = 5.5
I think it would be very surprising to get hastraits.int_trait = 5
be the result of that assignment. I would consider it a bug that 5.0
raises a TraitError, but I think that's something that should change in Integer, rather than force the addition of CInteger
, which would coerce all kinds of things, like '5'
and b'\9'
to integers, when they should probably raise errors.
I totally agree, explicit is better than implict and errors should never go unnoticed (or something like that).
One can probably distinguish at least three classes of numbers:
- python integers (
int
and in py2long
) - other types that always represent integer numbers (numpy array scalars and possibly 0-dimensional arrays of integer types)
- numeric types that may represent integer numbers, but also non-integer numbers
- types that may represent numbers, which might be integers.
It is a matter of definition what one calls coercion and what not, but I'd definitely want to have a trait that accepts the first two classes. I do not care too much if the values are kept as is or turned into python integer object (the latter could be an option for a coercing trait). I am actually undecided towards the third class, I'd tend to let traits reject them, but a design choice for a coercing trait could certainly be to accept e.g. float objects that represents an integer object. It definitely should coerce that object into one of the first two classes.
tl,dr; I want to be able to assign numpy integers to integer traits... Maybe #245 could solve that?