Why does Six.py use a custom class to search for MAXSIZE?

I read the six.py code in django utils , which for an implementation without Jython is trying to find MAXSIZE for int. Now, how this is done is interesting - instead of catching an exception in the expression itself, the operator is enclosed in the __len__ method in the user class. What could be the reason (s) for this?

 class X(object): def __len__(self): return 1 << 31 try: len(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X 

If I’m not mistaken, the same thing could be reduced to the bottom, right?

 try: 1 << 31 except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) 
+5
source share
1 answer

int in python3 is a multi-head class of a class that can represent machine ints, as well as big-ints; which is superior to the difference between int and long in python2. On python3, the int(1 << n) construct never throws an error.

So, to solve this, six uses a neat trick that forces python to sew something in a machine the size of an int. The built-in len always tries to convert the return value of __len__ to a machine size value:

 >>> class Lengthy(object): ... def __init__(self, x): ... self.x = x ... def __len__(self): ... return self.x ... >>> int(1<<100) 1267650600228229401496703205376L >>> type(int(1<<100)) <type 'long'> >>> len(Lengthy(1<<100)) Traceback (most recent call last): File "<ipython-input-6-6b1b77348950>", line 1, in <module> len(Lengthy(1<<100)) OverflowError: long int too large to convert to int >>> 

or, in Python 3, the exception is slightly different:

 >>> len(Lengthy(1<<100)) Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: cannot fit 'int' into an index-sized integer >>> 
+4
source

All Articles