Monday, September 8, 2014

Argument Unpacking in Python (holy balls!)

Hey y'all, I'm here to teach you about Argument Unpacking.  Please, try to remain in your seats.
Woah that guy just got Argument Unpacking













So I had to do some screen scraping (follow that link).  Yuck, right?  Except no, I get some weird sick pleasure out of screen scraping (I volunteer to do it).

(Skip this if you know what screen scraping is)
So in short screen scraping is when you translate a hard-to-traverse website into a nice data structure like json.

Anyways, I was writing a screen scraper for the paint mixer.  I made classes for my data templates (yay go me).  At first, I thought it would be easy to just iterate through the table cells using BeautifulSoup (a very cool and excellent Python html parser).  That was not good.


for cell in cells:
   if cellNumber == 0:
    try:
     cardNumber = cell.contents[0]
    except IndexError:
     cardNumber = None
   elif cellNumber == 1:
    try:
     firstName = cell.contents[0]
    except IndexError:
     firstName = None
   elif cellNumber == 2:
    try:
     lastName = cell.contents[0]
    except IndexError:
     lastName = None
   elif cellNumber == 3:
    try:
     email = cell.contents[0]
    except IndexError:
     email = None
   elif cellNumber == 4:
    try:
     balance = cell.contents[0]
    except IndexError:
     balance = None

^^^ Holy Mother that is bad

I knew Python just had to have a better alternative to this (the word pythonic is a thing, talk about a language dating itself), so I did me some googling and came upon a glorious find: argument unpacking.
This is going to be you in a few sentences











The Astute Reader (tm):  Wow, that traversal Max was talking about seemed really array-like!  I bet there's an easier way to do that!
Me:  Gee thanks captain obvious!  You don't think I was lamenting that with every line I wrote?  I knew I was so close!
The Astute Reader (tm):  Ok, that was an obvious lead-in to Argument Unpacking.  Let's have it, then.

Ok, here it is...drumroll please.

I have a method that takes 6 parameters:

def method_with_lots_of_freaking_parameters(x1, y1, x2, y2, x3, y3):
 print "Haha I'm not even going to use those arguments!"

And I have a list with those parameters stored just itching to be passed to that method
superswaglist = [5, 1, 3, 6, 6, 6]  #wow this is super contrived huh?

Without Argument Unpacking, this is how you'd have to call that method
method_with_lots_of_freaking_parameters(superswaglist[0], superswaglist[1], superswaglist[2], superswaglist[3], superswaglist[4], superswaglist[5])  #puke

But with this blessed tool (In the Name of Python We Pray), we simply call

method_with_lots_of_freaking_parameters(*superswaglist)  #wow such ease
I couldn't agree more
This tool condensed 56 lines of code into one for my screen scraper tool.  Be excited.

PS If you want a tutorial on screen scraping let me know in the comments!

1 comment: