spudtater: (Default)
([personal profile] spudtater May. 25th, 2006 11:53 pm)
Have been programming at work, and rediscovering the joys of programming quirks. Specifically, Python quirks.
def foo1():
   x = ['data']
   bar1( x )
   print x

def bar1( liszt ):
   liszt[0] = 'spock'

>>> foo1()
['spock']

def foo2():
   x = ['data']
   bar2( x )
   print x

def bar2( liszt ):
   liszt = ['spock']

>>> foo2()
['data']

Well, you've probably seen that one before. I ended up writing a program which depended on that property to function properly. It was recursive, and passed round a list as a parameter, which needed to be altered by various instances of the function. Then just as I was about to fire it up, I realised that in one case I didn't need to alter just the end of the list, but change it completely. As a hack, I ended up writing this function:
def replacelist( list1, list2 ):
   """ Replace the data in list 1 with that of list 2, while
   maintaining the original list pointer """
   while list1: del list1[0]
   for item in list2: list1.append( item )

I feel dirty.

On a completely unrelated note: not sure whether I want to go out to the pub tomorrow (oops! today now!) or just stay in. Anybody else going to be there?

From: [identity profile] norgg.livejournal.com


Ew. Ew. Ew.
There must be nicer ways of doing this, though I don't really know python well enough to spot them.
ext_79424: Line drawing of me, by me (Default)

From: [identity profile] spudtater.livejournal.com


The functional approach:



Make the list a return value. My function was already returning a string, but as Python allows you to return a tuple, I could have altered it like so:



return (returnstr, liszt)



But I couldn't be bothered.



The object-oriented approach:



Create a simple holder for the list:



class listholder:
   def __init__( self, liszt ):
      self.liszt = liszt


And then just use a combination of l = listholder( data ) and l.liszt = newdata. The object reference will be preserved.


From: [identity profile] norgg.livejournal.com


Ok, the functional approach there is nice enough, aye. That OO approach still makes me twitch though. The way I'd do it in ruby would be:
class Array
  def replace(newArray)
    clear
    newArray.each{|elem| self << elem}
  end
end

Which adds a replace method to the Array class(which are very similar to python lists) and both alters and returns the object itself.

But then that's ruby...
.

Profile

spudtater: (Default)
spudtater

Most Popular Tags

Powered by Dreamwidth Studios

Style Credit

Expand Cut Tags

No cut tags