[Tutor] 2.7.3 documentation gripe (feel free to ignore)

2012-09-14 Thread Ray Jones

6.5. The del
http://docs.python.org/reference/simple_stmts.html#del statement

*del_stmt* ::=  del target_list 
http://docs.python.org/reference/simple_stmts.html#grammar-token-target_list

Deletion is recursively defined very similar to the way assignment is
defined. Rather than spelling it out in full details, here are some hints.

===

They call this DOCUMENTATION??? it's similar to such and such - you
figure it outhere are the hints!

Bah! I hope their code is better than the documentation. :-p


Ray

P.S. Not a request for help - I can find the answers. Just a comment on
the documentation in general

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] index of elements in numpy array

2012-09-14 Thread Bala subramanian
Thank you all for the answer. Below, i have pasted a sample code that
shows what i am intending to do. The code fails at line 13 as numpy
array dnt have a index attribute.

  1 #!/usr/bin/env python
  2 import numpy as np
  3
  4 a=np.array([1,2,3,4,5,6,7,8,9,10,11,12])
  5
  6 b=np.reshape(a,(3,4))
  7
  8 z=[100,101,102,103,104,106,107,108,109,110,111,112]
  9
 10 # loop over each row
 11 for i1, d1 in enumerate(b):
 12 # each x in d1 - value in z corresponding to index of x in d1
 13 d1=[x-z[d1.index(x)] for x in d1]

If d1 is a simple list, i can fetch the index of its element as
d1.index(x). So i would like to know how can achieve the same with
numpy array.

Thanks once again,
Bala

On Fri, Sep 14, 2012 at 12:39 AM, Dave Angel d...@davea.name wrote:
 On 09/13/2012 04:16 PM, Bala subramanian wrote:
 Friends,
 I have a 2D matrix (a numpy array) and i am looping over each row in
 the matrix. I would like to know how i can find the index of each
 element in a while looping a row. Is there any function in numpy.

 Thanks


 Perhaps you're asking a more general question.  When iterating over a
 collection, sometimes you not only want the object, but you also want
 the index you might have used to fetch it.

 for row in rows:
dosomething with row

 for index, row in enumerate(rows):
dosomething with row and with index

 Now if rows be a list, or whatever numpy decides to call it, then you
 can manipulate the particular one with rows[index].



 --

 DaveA




-- 
C. Balasubramanian
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] (2.7.3) Inexplicable change of type

2012-09-14 Thread Ray Jones
The code:

def split_string(source,splitlist):
idx = 0
   
while idx  len(splitlist):
   
if splitlist[idx] in source:
source = ' '.join(source.split(splitlist[idx]))
   
idx += 1
   
source = source.split(' ')
print source is, source, and its type is, type(source) # --
while '' in
source:# --
source = source.remove('')

return source

out = split_string('Hi! I am your Assistant Instructor, Peter.', '! ,.')
print out


The result:

source is ['Hi', '', 'I', 'am', 'your', 'Assistant', 'Instructor', '',
'Peter', ''] and its type is type 'list'
Traceback (most recent call last):
  File /tmp/pytmp.py, line 18, in module
out = split_string('Hi! I am your Assistant Instructor, Peter.', '! ,.')
  File /tmp/pytmp.py, line 13, in split_string
while '' in source:
TypeError: argument of type 'NoneType' is not iterable

Between the two arrows, 'source' inexplicably switches from type list
to type NoneType. Why?


Ray
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] index of elements in numpy array

2012-09-14 Thread Peter Otten
Bala subramanian wrote:

 Thank you all for the answer. Below, i have pasted a sample code that
 shows what i am intending to do. The code fails at line 13 as numpy
 array dnt have a index attribute.
 
   1 #!/usr/bin/env python
   2 import numpy as np
   3
   4 a=np.array([1,2,3,4,5,6,7,8,9,10,11,12])
   5
   6 b=np.reshape(a,(3,4))
   7
   8 z=[100,101,102,103,104,106,107,108,109,110,111,112]
   9
  10 # loop over each row
  11 for i1, d1 in enumerate(b):
  12 # each x in d1 - value in z corresponding to index of x in d1
  13 d1=[x-z[d1.index(x)] for x in d1]
 
 If d1 is a simple list, i can fetch the index of its element as
 d1.index(x). So i would like to know how can achieve the same with
 numpy array.

How about

 b - np.array(z[:4])
array([[-99, -99, -99, -99],
   [-95, -95, -95, -95],
   [-91, -91, -91, -91]])

(Note that the result may differ from that of your code if d1 contains 
duplicate values)

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (2.7.3) Inexplicable change of type

2012-09-14 Thread Steven D'Aprano

On 14/09/12 18:43, Ray Jones wrote:


Between the two arrows, 'source' inexplicably switches fromtype list
totype NoneType. Why?


source.remove('') does not do what you think it does. Checking the
Fine Manual is always a good idea, or experimentation at the interactive
interpreter:


py source = list('abcd')
py result = source.remove('a')
py result is None
True
py source
['b', 'c', 'd']


The list.remove method operates on the list in place, and like (nearly?)
all such in-place methods, it returns None.

So source = source.remove(' ') replaces source with None instead of the
list, which is then lost.

By the way, at the interactive interpreter you can also say:


help(list.remove)

to read some documentation on the method.



--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (2.7.3) Inexplicable change of type

2012-09-14 Thread Peter Otten
Ray Jones wrote:

 source = source.remove('')

list.remove() modifies the list in-place and therefore by convention returns 
None:

 source = [one, , three]
 source.remove()
 source
['one', 'three']


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (2.7.3) Inexplicable change of type

2012-09-14 Thread eryksun
On Fri, Sep 14, 2012 at 4:43 AM, Ray Jones crawlz...@gmail.com wrote:

 source = source.remove('')

 Between the two arrows, 'source' inexplicably switches from type list
 to type NoneType. Why?

 x = [1,2,3]
 result = x.remove(1)
 type(result)
type 'NoneType'
 x
[2, 3]

Methods that mutate an object typically return None. Just call
remove() without reassignment.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (2.7.3) Inexplicable change of type

2012-09-14 Thread Ray Jones
On 09/14/2012 02:07 AM, Steven D'Aprano wrote:
 On 14/09/12 18:43, Ray Jones wrote:

 Between the two arrows, 'source' inexplicably switches fromtype list
 totype NoneType. Why?

 source.remove('') does not do what you think it does. Checking the
 Fine Manual is always a good idea, or experimentation at the interactive
 interpreter:
[...]
 So source = source.remove(' ') replaces source with None instead of the
 list, which is then lost.

 By the way, at the interactive interpreter you can also say:


 help(list.remove)

 to read some documentation on the method.


I did use the help() on that, but I missed the 'in place' part. That
would explain things! :))

Thanks.


Ray
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (2.7.3) Inexplicable change of type

2012-09-14 Thread Ray Jones
Thanks for the responses. I knew it had to be something stupid ;)).


Ray
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 2.7.3 documentation gripe (feel free to ignore)

2012-09-14 Thread Steven D'Aprano

On 14/09/12 17:29, Ray Jones wrote:


 6.5. The del
 http://docs.python.org/reference/simple_stmts.html#del  statement

[...]

They call this DOCUMENTATION??? it's similar to such and such - you
figure it outhere are the hints!

Bah! I hope their code is better than the documentation. :-p



*shrug*

Look at the size of the documentation for assignments, two and a half
pages. Deletion is almost exactly the same except there is no target on
the left hand side of the operator.

I'm honestly not sure that there would be any advantage to spelling out
in gory detail over a page and a half how del works, but if you think the
documentation is lacking, remember that Python is an open-source project
and community input is welcome and desired.


--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 2.7.3 documentation gripe (feel free to ignore)

2012-09-14 Thread Ray Jones
On 09/14/2012 02:32 AM, Steven D'Aprano wrote:
 On 14/09/12 17:29, Ray Jones wrote:

  6.5. The del
  http://docs.python.org/reference/simple_stmts.html#del  statement
 [...]
 They call this DOCUMENTATION??? it's similar to such and such - you
 figure it outhere are the hints!

 I'm honestly not sure that there would be any advantage to spelling out
 in gory detail over a page and a half how del works, but if you think the
 documentation is lacking, remember that Python is an open-source project
 and community input is welcome and desired.

Great reply to sour grapes! lol  I'll remember that ;).


Ray
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] index of elements in numpy array

2012-09-14 Thread eryksun
On Fri, Sep 14, 2012 at 4:36 AM, Bala subramanian
bala.biophys...@gmail.com wrote:

  10 # loop over each row
  11 for i1, d1 in enumerate(b):
  12 # each x in d1 - value in z corresponding to index of x in d1
  13 d1=[x-z[d1.index(x)] for x in d1]

 If d1 is a simple list, i can fetch the index of its element as
 d1.index(x). So i would like to know how can achieve the same with
 numpy array.

In general you don't want to loop over and enumerate a NumPy array.
That's a lot slower than using vectorized operations (just like in
MATLAB) and broadcasting. See Peter Otten's answer.

For an 'index' operation you have a couple of options. To begin with,
a test returns a bool array:


 d = np.array([1,2,1,2,1])

 d == 1
array([ True, False,  True, False,  True], dtype=bool)


You can use this bool array to index the source array:


 d[d == 1]
array([1, 1, 1])

 d[d == 1] = 3
 d
array([3, 2, 3, 2, 3])


To get the indexes, use nonzero or where:


 np.nonzero(d == 2)
(array([1, 3]),)

 np.where(d == 2)
(array([1, 3]),)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Musical note on python

2012-09-14 Thread eryksun
On Thu, Sep 13, 2012 at 8:37 PM, D.V.N.Sarma డి.వి.ఎన్.శర్మ
dvnsa...@gmail.com wrote:

 Error: name data undefined

 import wave
 import winsound
 from cStringIO import StringIO

 def get_wave(data):
 f = StringIO()
 w = wave.open(f, 'w')
 w.setnchannels(1) # mono
 w.setsampwidth(2) # 2 bytes
 w.setframerate(48000) # samples/second
 w.writeframes(data)
 return f.getvalue()


 Then play the sound like this (_untested_):


 wave_data = get_wave(data)
 windsound.PlaySound(wave_data, winsound.SND_MEMORY)


data is a byte string of packed samples. For example, the function
packwave() converts a sequence of floats into a byte string. It
assumes the input is in the range [-1.0, 1.0]. It scales this range to
[-32767, 32767]. Each scaled value is packed as 2 bytes in little
endian order. That means the order is (low byte, high byte).

For example, 32767 becomes \xff\x7f, where 0xff (255) is the low
byte and 0x7f (127) is the high byte. You can calculate the value as
follows: 255 + 127*256 = 32767. Since the format is 2's complement,
the next value up, \x00\x80, wraps around to -32768. Then \x01\x80
is -32767, and so on, up to -1 at \xff\xff.

http://docs.python.org/library/struct

http://en.wikipedia.org/wiki/Endianness

http://en.wikipedia.org/wiki/Two%27s_complement
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] is this use or abuse of __getitem__ ?

2012-09-14 Thread Albert-Jan Roskam
Hi,

I defined a __getitem__ special method in a class that reads a binary data file 
using a C library. The docstring should clarify
the purpose of the method. This works exactly as I intended it, however, the 
key argument is actually used as an index
(it also raises an IndexError when key is greater than the number of records 
in the file). Am I abusing the __getitem__ method, or is this just a creative 
way of using it?


# Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] 
on win32

    def __getitem__(self, key):
     This function reports the record of case number key.
    For example: firstRecord = FileReader(fileName)[0] 
    if not isinstance(key, (int, float)):
    raise TypeError
    if abs(key)  self.nCases:
    raise IndexError
    retcode1 = self.iomodule.SeekNextCase(self.fh, ctypes.c_long(int(key)))
    self.caseBuffer, self.caseBufferPtr = self.getCaseBuffer()
    retcode2 = self.iomodule.WholeCaseIn(self.fh, self.caseBufferPtr)
    record = struct.unpack(self.structFmt, self.caseBuffer.raw)
    if any([retcode1, retcode2]):
    raise RuntimeError, Error retrieving record %d [%s, %s] % \
  (key, retcodes[retcode1], retcodes[retcode2])
    return record
 
Regards,
Albert-Jan


~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~ 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] index of elements in numpy array

2012-09-14 Thread Oscar Benjamin
On 14 September 2012 11:05, eryksun eryk...@gmail.com wrote:

 On Fri, Sep 14, 2012 at 4:36 AM, Bala subramanian
 bala.biophys...@gmail.com wrote:
 
   10 # loop over each row
   11 for i1, d1 in enumerate(b):
   12 # each x in d1 - value in z corresponding to index of x in d1
   13 d1=[x-z[d1.index(x)] for x in d1]
 
  If d1 is a simple list, i can fetch the index of its element as
  d1.index(x). So i would like to know how can achieve the same with
  numpy array.


Whether you use a list or a numpy array, iterating over the elements and
then trying to get the index of each value from the value itself is
inefficient. It's also leads to problems when the array/list contains
duplicate values. I think the way to replace your line 13 would be to use:

d1 = [x - z[n] for n, x in enumerate(d1)]

There is another problem though which is that you're assigning to d1 which
is the same name that you've used for your loop variable in the outer loop.
This means that you're throwing away the values you compute. Are you hoping
that by assigning to d1, the values would get stored in b?

Perhaps what you need to do is:

b[i1, :] = [x - z[n] for n, x in enumerate(d1)]

This way the values will get stored in b. If you actually want them to be
stored in another array, say c, then create that array before the loop with

c = np.zeros_like(b)

If this is what you're trying to do, though you would be better off just
using Peter's suggestion:

c = b - np.array(z[:b.shape[1]])

so that you don't need a loop at all.


 In general you don't want to loop over and enumerate a NumPy array.
 That's a lot slower than using vectorized operations (just like in
 MATLAB) and broadcasting. See Peter Otten's answer.

 For an 'index' operation you have a couple of options. To begin with,
 a test returns a bool array:


  d = np.array([1,2,1,2,1])

  d == 1
 array([ True, False,  True, False,  True], dtype=bool)


 You can use this bool array to index the source array:


  d[d == 1]
 array([1, 1, 1])

  d[d == 1] = 3
  d
 array([3, 2, 3, 2, 3])


 To get the indexes, use nonzero or where:


  np.nonzero(d == 2)
 (array([1, 3]),)

  np.where(d == 2)
 (array([1, 3]),)


The suggestions above from eryksun are closer to what actually happens when
you use the index function on a list, but you should consider whether or
not that is really what you want to do.

Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (2.7.3) Inexplicable change of type

2012-09-14 Thread Emile van Sebille

On 9/14/2012 1:43 AM Ray Jones said...

The code:

snip

 source = source.remove('')
 return source


To round things out, here's one way to do what I expect you're expecting:

 r=range(10)
 a = r.pop(r.index(4))
 a
4
 r
[0, 1, 2, 3, 5, 6, 7, 8, 9]


Emile






___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is this use or abuse of __getitem__ ?

2012-09-14 Thread eryksun
On Fri, Sep 14, 2012 at 8:16 AM, Albert-Jan Roskam fo...@yahoo.com wrote:

 Am I abusing the __getitem__ method, or is this just a creative way of using 
 it?

No, you're using it the normal way. The item to get can be an index, a
key, or even a slice.

http://docs.python.org/reference/datamodel.html#object.__getitem__

 if not isinstance(key, (int, float)):
 raise TypeError

Instead you could raise a TypeError if not hasattr(key, '__int__')
since later you call int(key).

 if abs(key)  self.nCases:
 raise IndexError

You might also want to support slicing. Here's an example:

http://stackoverflow.com/a/2936876/205580
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (2.7.3) Inexplicable change of type

2012-09-14 Thread eryksun
On Fri, Sep 14, 2012 at 8:37 AM, Emile van Sebille em...@fenx.com wrote:

  source = source.remove('')

 To round things out, here's one way to do what I expect you're expecting:

 r=range(10)
 a = r.pop(r.index(4))
 a
4
 r
[0, 1, 2, 3, 5, 6, 7, 8, 9]

Ray was probably thinking in terms of immutable objects such as strings:

 1.replace('1', '2').replace('2', '3')
'3'

Since Python doesn't do in-place operations on strings, it has to
return a new object for each call to replace().

list.pop() returns a value, but Ray doesn't want the value. Splitting
on a single character leaves empty strings between consecutive runs of
the character (or at the edges). For example, splitting 'babbbab' on
'b' returns ['', 'a', '', '', 'a', '']. Ray is looping until all of
the empty strings have been removed from the list. It's a completely
in-place modification.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is this use or abuse of __getitem__ ?

2012-09-14 Thread Steven D'Aprano

On 14/09/12 22:16, Albert-Jan Roskam wrote:

Hi,

I defined a __getitem__ special method in a class that reads a binary data
file using a C library. The docstring should clarify the purpose of the
method. This works exactly as I intended it, however, the key argument is
actually used as an index (it also raises an IndexError whenkey  is
greater than the number of records in the file). Am I abusing the __getitem__
method, or is this just a creative way of using it?


No, that's exactly what __getitem__ is for. It does double-duty for key-lookup
in mappings (dict[key]) and index-lookup in sequences (list[index]).

You can also support ranges of indexes by accepting a slice argument.

Another comment below:



# Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] 
on win32

 def __getitem__(self, key):
  This function reports the record of case numberkey.
 For example: firstRecord = FileReader(fileName)[0] 
 if not isinstance(key, (int, float)):
 raise TypeError


Floats? Do you actually have have case number (for example)
0.14285714285714285 ?

For this case, I think it is reasonable to insist on exactly an int,
and nothing else (except possibly a slice object, to support for
example obj[2:15]).



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simon game issues

2012-09-14 Thread Matthew Ngaha
 It would appear you're running some form of event loop, such as
 wxpython, tkinter, pygame, or whatever.  If so, you have to do your
 delays using the mechanism that system defines, not using sleep().  As
 you've discovered, sleep() stops the whole thread, and that's not what
 you want.  What you want is to set an event to fire at some measured
 time in the future, so the actual waiting is done inside the event loop.


hey i looked at the livewires documentation and pulled up the timer
information. im struggling to figure out how to use its explanation. i
need to use it at 2 different parts of the program. 1st when the game
starts i need to create my sprite objects so they appear before my
animation objects:

red = Sprite(colour = Colours.red, x = 250, y = 255)
games.screen.add(red)

#timer event delay goes here so the animations don't start as soon as
the game is opened, before the coloured sprites as they've been doing.

self.create_animations()
-


i also need a timer event when i display my sequence of animation
objects so they dont show on screen simultaneously. so:

#1st animation
red_animation = Animation(images = c_red, x = 250, y = 255,
 repeat_interval = 4, n_repeats = 1)
games.screen.add(red_ani)
red_sound.play()

#Timer event to go here, so next animation in sequence goes after the
timed pause.

#2nd animation
blue_animation = Animation(images = c_blue, x = 373, y = 255,
   repeat_interval = 4, n_repeats = 1)
games.screen.add(blue_ani)
blue_sound.play()

do you think you can offer any help how to implement the timer code or
function? i will provide the link to the page, but here's the relevant
code:


Timer
The Timer class is a class you can add to something which is also a
subclass of Object, to make an object that performs actions at regular
intervals. A class which is intended to be used with another class is
called a mix-in. For instance, if you wanted to make a new class of
your own which was a Circle and also a Timer, you would define the
class by saying class MyClass (games.Circle, games.Timer):
 • init_timer (interval)

interval is how often the tick method is called, measured in timer
ticks. How long a tick is depends on the fps argument you give to the
Screen‘s mainloop method. Setting fps to 50 means a tick is 1/50 of a
second.

You must call this method emph{after} you have called the init_ method
for the Object subclass you are using.

• stop ()

Stop the timer running. It continues to exist, but doesn’t count any more.

• start ()

Starts the timer again. A full interval will elapse before it ticks.

• get_interval ()

Gets the current interval.

• set_interval (interval)

Sets the current interval.

• tick ()

This method must be supplied by you, by subclassing the Timer class.

http://www.geon.wz.cz/livewires/w-livewires.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is this use or abuse of __getitem__ ?

2012-09-14 Thread Albert-Jan Roskam
 On 14/09/12 22:16, Albert-Jan Roskam wrote:

  Hi,
 
  I defined a __getitem__ special method in a class that reads a binary data
  file using a C library. The docstring should clarify the purpose of the
 method. This works exactly as I intended it, however, the key 
 argument is
  actually used as an index (it also raises an IndexError whenkey  is
 greater than the number of records in the file). Am I abusing the 
 __getitem__
 method, or is this just a creative way of using it?
 
 No, that's exactly what __getitem__ is for. It does double-duty for 
 key-lookup
 in mappings (dict[key]) and index-lookup in sequences (list[index]).
 
 You can also support ranges of indexes by accepting a slice argument.

 

COOL! I was already wondering how this could be implemented. Dive into Python 
is pretty exhaustive wrt special methods,
but I don't think they mentioned using the slice class. Below is how I did it. 
Is it recommended to define the geitem() function inside the __getitem__() 
method? I was thinking I could also define a _getitem() private method. Hmmm, 
maybe getitem() is redefined over and over again the way I did it now?


    def __getitem__(self, key):
     This function reports the record of case number key.
    For example: firstRecord = SavReader(savFileName)[0] 
    def getitem(key):
    retcode1 = self.iomodule.SeekNextCase(self.fh, 
ctypes.c_long(int(key)))
    self.caseBuffer, self.caseBufferPtr = self.getCaseBuffer()
    retcode2 = self.iomodule.WholeCaseIn(self.fh, self.caseBufferPtr)
    record = struct.unpack(self.structFmt, self.caseBuffer.raw)
    if any([retcode1, retcode2]):
    raise RuntimeError, Error retrieving record %d [%s, %s] % \
  (key, retcodes[retcode1], retcodes[retcode2])
    return record
    if isinstance(key, slice):
    records = [getitem(i) for i in range(*key.indices(self.nCases))]
    return records
    elif hasattr(key, __int__): # isinstance(key, (int, float)):
    if abs(key)  (self.nCases - 1):
    raise IndexError
    else:
    key = self.nCases + key if key  0 else key
    record = getitem(key)
    return record
    else:
    raise TypeError   


 Another comment below:
 
 
  # Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit 
 (Intel)] on win32
 
       def __getitem__(self, key):
            This function reports the record of case 
 numberkey.
           For example: firstRecord = FileReader(fileName)[0] 
 
           if not isinstance(key, (int, float)):
               raise TypeError
 
 Floats? Do you actually have have case number (for example)
 0.14285714285714285 ?
 
 For this case, I think it is reasonable to insist on exactly an int,
 and nothing else (except possibly a slice object, to support for
 example obj[2:15]).
 

I also accepted floats as a convenience. I had examples in mind like: record = 
data[1.0] . Kind of annoying when this raises a TypeError.
But in your example makes perfect sense to raise such an exception.

Eryksun, Steven: Thanks!!!

Albert-Jan
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] (no subject)

2012-09-14 Thread Johny Rei
hi  to all readers, i 'm a newbie and i'm interested to learn python 
programming, can anybody please guide me out to learn basic to advance python 
programming, be actually can anyone out there should suggest a free book that i 
can read it on just to learn from as a newbie to python programming? i can be 
kindly respect and appreciate the guidance you can  recommend it to me..thnx___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor