2

I got the following problem in Python code.

The error is:

Traceback (most recent call last): File "cmd.py", line 16, in <module>
    func(b="{cmd} is entered ...") # Error here
File "cmd.py", line 5, in func
    exceptMsg = b.format(errStr=errStr, debugStr=debugStr)
KeyError: 'cmd'

The code:

import re

def func(errStr = "A string", b = "{errStr}\n{debugStr}"):
    debugStr = "Debug string"
    exceptMsg = b.format(errStr=errStr, debugStr=debugStr)
    raise ValueError(exceptMsg)

try:
    '''
    Case 1: If user invokes func() like below, error produced.
    Possible explanation: Paramter b of func() is looking keyword   
    'errStr' further down in func() body, but I am passing it keyword
    'cmd' instead. What to change to make the code work?
    '''
    #cmd = "A crazy string"             # Comment, make code pass 
    #func(b="{cmd} is entered ...")     # Error here

    # Case 2: If user invokes func() like below, OK.
    errStr = "A crazy string"
    func(b="{errStr} is entered")

except ValueError as e:
    err_msg_match = re.search('A string is entered:', e.message)
    print "Exception discovered and caught!"

1) If the function interface func() is preserved, what code to change?

2) If I must modify the function interface, how'd I go about making it a clean code change?

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
user1972031
  • 547
  • 1
  • 5
  • 19
  • Output (continued): ---------------- $ python cmd.py Traceback (most recent call last): File "cmd.py", line 16, in func(b="{cmd} is entered ...") # Error here File "cmd.py", line 5, in func exceptMsg = b.format(errStr=errStr, debugStr=debugStr) KeyError: 'cmd' $ python cmd.py Exception discovered and caught! – user1972031 Apr 24 '15 at 09:35
  • What error do you get? –  Apr 24 '15 at 09:36
  • 2
    Please put that into your question, properly formatted. – Daniel Roseman Apr 24 '15 at 09:36
  • Its probably best to add the output to the post itself, no? – ODiogoSilva Apr 24 '15 at 09:37
  • Note that the variable `errStr` ("A crazy string") isn't used for formatting and its presence has no effect on anything. – molbdnilo Apr 24 '15 at 09:48

1 Answers1

3

b.format(errStr=errStr, debugStr=debugStr) only passes errStr and debugStr to replace placeholders. If b contains any other placeholder variables it will fail.

You have:

b = "{cmd} is entered ..."

There is nothing to match {cmd}

If you wanted to pass cmd to func, you can do it with keyword arguments:

def func(errStr = "A string", b = "{errStr}\n{debugStr}", **kwargs):
    debugStr = "Debug string"
    exceptMsg = b.format(errStr=errStr, debugStr=debugStr, **kwargs)
    raise ValueError(exceptMsg)

And use as:

func(b="{cmd} is entered ...", cmd="A crazy string")
Community
  • 1
  • 1
Peter Wood
  • 23,859
  • 5
  • 60
  • 99