[Tutor] Fwd: Sys.argv read parameters
Danny Yoo
dyoo at hashcollision.org
Thu Apr 18 21:10:02 CEST 2013
Ok, good. This is _much_ more realistic code, and demonstrates why
seeing context is important.
My suggestion to do it computationally is totally invalid here. :P
There's a lot of variation here, due to the access paths through the
JSON that you're walking. You're essentially defining a very
lightweight domain-specific language, technically. The semantics of
the commands appear to be: walk the JSON of a certain path. A
dispatch table here is _very_ appropriate.
The values in your dispatch table, however, should not be literal code
that you want to evaluate: rather, they should just hold an inert
path. The act of using the dispatch table should take a path and then
apply it to the JSON in question.
(I am trying _very_ hard not to say the word "eval" here, because it's
just dangerous in this context.)
Here's what the interpretation part of your language might looks like:
#####################################################################
def p(*elts):
"""Construct a representation of a path.
(We'll cheat a little by using a list of strings.)"""
return elts
commands = {
'uptime' : p('serverStatus', 'uptime'),
'globalLock_lockTime' : p('serverStatus', 'globalLock', 'lockTime')
## Fill me in with more elements.
}
def lookup(data, cmdName):
path = commands[cmdName]
for p in path:
data = data[p]
return data
## For example, let's mock up some sample data and see how this works.
sampleData = {'serverStatus' : {'uptime': 3,
'cpu load' : 1.11,
'globalLock' : { 'lockName' : 'sample
lock name',
'lockTime' : 42 }}}
print lookup(sampleData, 'uptime')
print lookup(sampleData, 'globalLock_lockTime')
#####################################################################
You should be able to see how to extend this to your realistic
example: just add more entries in your command. Note that I'm using a
function p() to construct the path: that's just for my own
convenience: you might be able to just strip it out and inline the
paths directly into the table.
(But having p there enables maintenance: we might need to extend the
system to do more than path lookup later on, in which case redefining
p makes it easy to change the representation of paths by modifying a
single place.)
More information about the Tutor
mailing list