3

I am using Python 2.7.3 and trying to understand why this script executes print statements out of order. i.e. the "-" prints AFTER the 2nd for loop.

My script:

def cheeseshop(kind, *arguments, **keywords):
    print "-- Do you have any", kind, "?"
    print "-- I'm sorry, we're all out of", kind
    for arg in arguments:
        print arg
    print "-" * 40
    keys = sorted(keywords.keys())
    for kw in keys:
        print kw, ":", keywords[kw]

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           {'shopkeeper':'Michael Palin',
           'client':"John Cleese",
           'sketch':"Cheese Shop Sketch"})

The output:

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
{'shopkeeper': 'Michael Palin', 'sketch': 'Cheese Shop Sketch', 'client': 'John Cleese'}
----------------------------------------

Why print "-"*40 execute BEFORE the dictionary as would be expected?

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895

1 Answers1

8

You didn't pass in the dictionary as keywords. Use the ** syntax to do so:

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           **{'shopkeeper':'Michael Palin',
           'client':"John Cleese",
           'sketch':"Cheese Shop Sketch"})

or don't use a dictionary at all:

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper='Michael Palin',
           client="John Cleese",
           sketch="Cheese Shop Sketch")
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Beat me to it. May want to note that the added paren's around the dict are not necessary. – cwallenpoole Jan 26 '13 at 18:48
  • Thank you Martijn! That explained it. – user2014142 Jan 26 '13 at 18:52
  • @cwallenpoole: indeed, I was going to check that but another conversation distracted me for a sec. – Martijn Pieters Jan 26 '13 at 18:52
  • I'd have been surprised if parens were necessary, this isn't PHP after all :) – phant0m Jan 26 '13 at 19:07
  • @phant0m: For the `**` and `*` cases, the parser can be a *little* picky. Can't think of an example of the top of my head right now, but for a dict literal it's indeed just fine. – Martijn Pieters Jan 26 '13 at 19:11
  • @cwallenpoole I'm not a hater. I just know for a fact that PHP's parser is less than optimal, to put it lightly. There's a reason PHP 5.4 has a *feature* called "function array dereferencing"... (Or [**here**](http://stackoverflow.com/a/11901500/383124) for other examples. (CTRL-F for "inconsistency") – phant0m Jan 26 '13 at 20:31