Paul
Paul

Reputation: 5974

"SyntaxError: keyword can't be an expression" using template

To a function I am passing in a string command and a list of strings ports An example:

command = "a b c {iface} d e f"
ports = ["abc", "adsd", "12", "13"]

These get passed to this function where I want to get multiple strings for command, replacing {iface} with each element in ports

def substitute_interface(command, ports):
    t = string.Template(command)
    for i in ports:
        print t.substitute({iface}=i)

I get the error in the title, what am i doing wrong?

Upvotes: 1

Views: 3985

Answers (2)

user395760
user395760

Reputation:

You have two errors:

  1. As the error message says, keyword arguments must be identifiers, whereas {iface} is a expression (specifically, a set containing the current value of iface). The braces around the iface name are markup to tell the substitution engine that there is something to be substituted there. To pass the value for that placeholder, just supply the key iface, ideally by writingt.substitute(iface=i).
  2. string.Template doesn't support that syntax, it wants $iface (or ${iface} if the former can't be used, but this case you can just use $iface). str.format supports this syntax, but apparently you don't want to use that.

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251106

From docs:

$identifier names a substitution placeholder matching a mapping key of "identifier"

So you need a $ sign otherwise the template will not be able to find the place-holder, and then pass iface = p to the substitute function or a dictionary.

>>> command = "a b c ${iface} d e f"  #note the `$`
>>> t = Template(command)
>>> for p in ports:
    print t.substitute(iface = p) # now use `iface= p` not `{iface}`
...     
a b c abc d e f
a b c adsd d e f
a b c 12 d e f
a b c 13 d e f

Without any modifications you can use this string "a b c {iface} d e f" with str.format:

for p in ports:
    print command.format(iface = p)
...     
a b c abc d e f
a b c adsd d e f
a b c 12 d e f
a b c 13 d e f

Upvotes: 2

Related Questions