pythonbuilt-inbuilt-in-types

How Python converts string to integer


This question is not about usage of int function, but rather how it is done internally.

Because source code is in C I don't understand what is going on there.

Maybe someone can explain how Python convert string "123" to integer 123. What operations are performed for it?


Solution

  • https://github.com/python/cpython/blob/2d305e1c46abfcd609bf8b2dff8d2065e6af8ab2/Objects/longobject.c#L2075-L2366 contains the implementation you're looking for. While understanding the C is useful, there is a large comment in the middle (starting on line 2132) that explains much of the approach.