[Tutor] More image manipulation (fwd)

Terry Carroll carroll at tjc.com
Wed Jun 8 00:45:54 CEST 2005

On Tue, 7 Jun 2005, D. Hartley wrote:

> OK. I tried them out and I do see the diffence. (btw, testit1 gave me
> the following error:
> Traceback (most recent call last):
>   File "<pyshell#72>", line 1, in ?
>     testit1()
>   File "<pyshell#68>", line 3, in testit1
>     del fromlist[0]
> IndexError: list assignment index out of range
> ... was that something you intended? that didnt happen with my
> original problem).

Interesting; I get this:

testit1: Denise problem
testit2: Python Gotcha #6
testit3: the right way

> Anyway I def notice the diff between 2 and 3, but see here's the thing:
> I think I *do* want it like #2, becaues I want it to keep returning
> the same list (i.e., move on and use line 2 (b), and then line 3 (c),
> and so on), rather than keep iterating over the same first line (a)
> over and over again.

Okay, gotcha.  

Here's my take on this sort of thing: I like to look at a method as a
black box, defined by the method signature and its call.  My basic rule is
that I don't every like a method to alter any data except what it passes

So... My approach, which I think is a little more clean and isolatable, is
to pass anything that the function needs to operate in as a parameter;  
then, if I want to alter that list, I create a new copy and pass that
back.  I have a deep distrust of globals.

So instead of this:

  def snip_first:
    delete alist[0]   # find alist via scoping rules

and calling it like this:

  alist = ['a', 'b', 'c']

I'd prefer to set it up like thi:

  def snip_first(input_list):
    output_list = alist[:]
    delete output_list[0]
    return output_list

  alist = ['a', 'b', 'c']

(Both of these are untested, I'm just winging it here.)

> I want to take the first line in the picture,
> rearrange the pixels, and pop that line into the new list that I can
> then (eventually) create a new image from. I *thought* my list was
> populated (it's 307200 pixels long, after all), but it wont work when
> i try to putdata it onto a new blank image.

I don't know about you, but if it were me, without that encapsulation, I'd 
have a tough time figuring out what's getting modified when.

> > > where does the variable named "fromlist" come from?  It's not passed into
> > > the method as a parameter.
> No, I had it defined right before the function. it pulls it in just
> fine. 

Yes, but global scoping often messes me up, so I always use a local scope.  
If it's not parameter-passed into or created in a method, I don't use it
in the method.

More information about the Tutor mailing list