Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python handles long ints differently on Windows and Unix

Tags:

python

The current number of milliseconds since the epoch is 1395245378429; on unix (64 bit / Ubuntu / python 2.7), you can do:

>>> t = 1395245378429
>>> type(t)
<type 'int'>
>>> t = 1395245378429L
>>> type(t)
<type 'long'>
>>> int(t)
1395245378429
>>> type(int(t)
<type 'int'>

but on Windows (also 64 bit / python 2.7), this happens:

>>> t = 1395245378429
>>> type(t)
<type 'long'>
>>> int(t)
1395245378429L
>>> type(int(t))
<type 'long'>

so, the following weird observations:

  • on Windows, int(<long>) returns a long
  • the same number is treated as a long in Windows, but an int on unix

I can't see anything obvious in the documentation to say this is correct behaviour; is there a (correct) way to convert the long to an int (i.e. so it can be used in a method which requires an int argument)

like image 268
ChrisW Avatar asked Oct 23 '25 19:10

ChrisW


1 Answers

Python uses C long for the int type, and even on Windows this is limited to 32-bit. You can see your platform's current maximum native int size by inspecting the sys.maxint value:

The largest positive integer supported by Python’s regular integer type. This is at least 2**31-1. The largest negative integer is -maxint-1 — the asymmetry results from the use of 2’s complement binary arithmetic.

and from the Numeric Types section:

Plain integers (also just called integers) are implemented using long in C, which gives them at least 32 bits of precision (sys.maxint is always set to the maximum plain integer value for the current platform, the minimum value is -sys.maxint - 1).

Unless you are directly interacting with a C extension library that doesn't support the Python long type, there is no need to worry about when Python uses int and when you need to use long. In Python 3, the separate long type has been removed entirely.

like image 67
Martijn Pieters Avatar answered Oct 26 '25 07:10

Martijn Pieters