Reputation: 4010
When I try to create this
self.cmds = {
'help' : self.cmdsHelp,
'write-start' : self.startWriter,
'write' : self.writeTo,
'read-start' : self.startReader,
'read' : self.readFrom
}
with the built-in dict()
function... i.e.
self.cmds = dict(
help = self.cmdsHelp,
write-start = self.startWriter,
write = self.writeTo,
read-start = self.startReader,
read = self.readFrom
)
... I get this error:
write-start = self.startWriter,
^
SyntaxError: keyword can't be an expression
The dictionary with the curly brackets ({}
) -- whatever special name that is -- works, but I cannot fathom why the "newer version" (the dict()
form) does not work. Is there something that I am missing, or do you just have to use the curly braces?
Each value in the dictionary is a function (and yes I did remove self.
, and I also tried to do both self.function()
and function()
so that when I called it I didn't have to do self.cmds[<input>]()
but could rather do self.cmds[<input>]
)
Upvotes: 0
Views: 117
Reputation: 1124090
Keyword arguments must be valid python identifiers. You cannot use -
in valid identifiers (you are trying to subtract two identifiers instead). dict()
is just a callable, and keyword arguments passed to it are no exception.
Use the {}
literal dict syntax instead:
self.cmds = {
'help': self.cmdsHelp,
'write-start': self.startWriter,
'write': self.writeTo,
'read-start': self.startReader,
'read': self.readFrom,
}
because then you can use any valid immutable & hashable value as keys.
Alternatively, use valid identifiers; replace -
with _
, a character that is allowed in indentifiers:
self.cmds = dict(
help=self.cmdsHelp,
write_start=self.startWriter,
write=self.writeTo,
read_start=self.startReader,
read=self.readFrom,
)
Any other alternatives get ugly real fast; you could use the dict literal syntax to produce a **kwargs
double-splat keyword argument mapping:
self.cmds = dict(
help=self.cmdsHelp,
write=self.writeTo,
read=self.readFrom,
**{
'read-start': self.startReader,
'write-start': self.startWriter,
}
)
but that's not any more readable, is it.
You can set those peskey non-identifier keys after the fact:
self.cmds = dict(
help=self.cmdsHelp,
write=self.writeTo,
read=self.readFrom,
)
self.cmds['read-start'] = self.startReader
self.cmds['write-start'] = self.startWriter
but that's more ugly still.
Note that dictionary displays (the official term for the syntax) are faster for the interpreter to process than are dict()
calls, as fewer bytecode instructions are used to build one and no function call is involved.
Upvotes: 6