Does Python's built-in function int still try to convert the submitted value even if the value is already an integer?
More concisely: is there any performance difference between int('42')
and int(42)
caused by conversion algorithm?
Does Python's built-in function int still try to convert the submitted value even if the value is already an integer?
More concisely: is there any performance difference between int('42')
and int(42)
caused by conversion algorithm?
If you pass an
int
object toint()
, you get the same object back (CPython 3.3.2):I don't know what you mean by "algorithmic performance difference", but it doesn't create a new object.
This is handled in function
long_long
inObjects/longobject.c
, as explained in more detail by thefourtheye:So, when the argument is already an
int
, the reference count is incremented and the same object returned.You can assume similar behavior for immutable types in general,. For example,
tuple(mytuple)
returns a new reference tomytuple
, while, by contrast,list(mylist)
creates a copy ofmylist
.Why don't you just compare both?
As per the comments in the source code,
So, if the input is a number,
__int__
function will be called on that object and the result will be returned. Internallynb_int
is an item in PyNumberMethods structure, which corresponds to the__int__
function. As per the latest source code at the time of this writing,long_long
is the function which corresponds to thenb_int
function, which is defined like thisHere
PyLong_checkExact
is a Macro, which just checks if the current object is really of type long. If it is true, it simply increases the reference count and returns the object as it is, nothing extra is done.If the input is in the form of a string, the string has to be converted to a number with
PyLong_FromUnicodeObject
function.