Counterintuitive behaviour of int() in python

后端 未结 4 1412
故里飘歌
故里飘歌 2021-02-04 23:07

It\'s clearly stated in the docs that int(number) is a flooring type conversion:

int(1.23)
1

and int(string) returns an int if and only if the

4条回答
  •  死守一世寂寞
    2021-02-04 23:24

    Sometimes a thought experiment can be useful.

    • Behavior A: int('1.23') fails with an error. This is the existing behavior.
    • Behavior B: int('1.23') produces 1 without error. This is what you're proposing.

    With behavior A, it's straightforward and trivial to get the effect of behavior B: use int(float('1.23')) instead.

    On the other hand, with behavior B, getting the effect of behavior A is significantly more complicated:

    def parse_pure_int(s):
        if "." in s:
            raise ValueError("invalid literal for integer with base 10: " + s)
        return int(s)
    

    (and even with the code above, I don't have complete confidence that there isn't some corner case that it mishandles.)

    Behavior A therefore is more expressive than behavior B.

    Another thing to consider: '1.23' is a string representation of a floating-point value. Converting '1.23' to an integer conceptually involves two conversions (string to float to integer), but int(1.23) and int('1') each involve only one conversion.


    Edit:

    And indeed, there are corner cases that the above code would not handle: 1e-2 and 1E-2 are both floating point values too.

提交回复
热议问题