Mutable numbers

skip at pobox.com skip at pobox.com
Tue Feb 21 11:35:40 EST 2006


    Rocco> def f():
    Rocco>      a = 12100
    Rocco>      b = 12100
    Rocco>      c = 121*100
    Rocco>      print a is b
    Rocco>      print a is c

That the object with value 12100 is referenced by both a and b is a side
effect of byte code compilation by CPython not an inherent property of
integer objects.  Nor is it an optimization performed by CPython on
integers.  As literals are collected during compilation they are only
inserted into the local constants tuple once.

    >>> def f():
    ...   a = "12,100"
    ...   b = "12,100"
    ...   c = "12," + "100"
    ...   print a is b
    ...   print a is c
    ...
    >>> f()
    True
    False
    >>> print f.func_code.co_consts
    (None, '12,100', '12,', '100')

    >>> def f():
    ...   a = 12100
    ...   b = 12100
    ...   c = 121*100
    ...   print a is b
    ...   print a is c
    ...
    >>> f()
    True
    False
    >>> print f.func_code.co_consts
    (None, 12100, 121, 100)

Skip



More information about the Python-list mailing list