mailRe: Why is a range in relax created as xrange objects which is not sliceable?


Others Months | Index by Date | Thread Index
>>   [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Header


Content

Posted by Edward d'Auvergne on December 10, 2013 - 13:56:
Hi,

Let me reply to this one by one.  The main reason is to do with speed,
memory usage, and Python 2.  In Python 3 this is not an issue.  This
is also the reason for the numpy.arange() function, but this one has
not been used in relax yet (though calculation speed ups might be
possible using this).  The problem is that the Python 2 implementation
of range() is horribly inefficient as it allocates all memory needed,
populates a list object with all the numbers, and then loops over
them.  xrange() and numpy.arange() do not do this, hence they make
calculations in relax much, much faster.  This is in a few select
places where the memory used is far too much or where the loop is
terminated early.  If you are not careful with range() in Python 2,
you can kill your program by using up all the RAM on the computer.
Back ~10 years this was actually quite a problem and it took me a long
time to debug and find the fatal range() calls.  In Python 3, I have a
feeling that xrange() was turned into range() and the old range() was
killed.  Therefore typing range(10) in the Python 3 prompt gives:

$ python3.2
Python 3.2.3 (default, Oct  1 2012, 22:45:55)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
range(10)
range(0, 10)


So relax should never rely on range() to create a list, as in the
future when Python 2 dies, it will not be a list.  However:

list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

This behaviour works from Python 1.5 onwards.  There should be a lot
of information on the web about the reason why xrange() exists.  Note
that as soon as wxPython supports Python 3 fully, then relax's main
target will be Python 3.

Regards,

Edward




On 10 December 2013 12:47, Troels Emtekær Linnet <tlinnet@xxxxxxxxxxxxx> 
wrote:
Hi Edward.

I wonder why range objects in relax by default are created as
xrange objects?

I think this is related to the error when importing matplotlib.
from pylab import *

-------
relax> M31=range(10)
relax> type(M31)
<type 'xrange'>
relax> print M31[:7]
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: sequence index must be integer, not 'slice'
-----

Best
Troels

_______________________________________________
relax (http://www.nmr-relax.com)

This is the relax-devel mailing list
relax-devel@xxxxxxx

To unsubscribe from this list, get a password
reminder, or change your subscription options,
visit the list information page at
https://mail.gna.org/listinfo/relax-devel




Related Messages


Powered by MHonArc, Updated Tue Dec 10 14:40:06 2013