For my first post, I'd like to describe a rather simple, and no-doubt popular technique that I have been using recently while coding in python. This technique is what I call a 'keyword argument'. Inspired by the type of argument in python that can be passed to a function as follows:
def foo(**kwargs):
for (key,value) in kwargs.items():
print "%s for %s" % (key,value)
if __name__ == "__main__":
foo(a = 1, b = 2, c = 3)
the output of this program is of course (or some permutation of the following): a for 1
c for 3
b for 2
now what is interesting about this idea? It is a fairly standard way of passing variable-length arguments where values are assigned to variables. The way it has interested me is to borrow this kind of pattern, except instead of using a dictionary built by the python interpreter out of arguments to a function, I use a "command" function which builds this dictionary from some input. A simplified version is as follows (please ignore the naive regex):
def command(self, command_string):
command_root = re.findall(r"^(\w+)",command_string)
key_argument_tuples = re.findall(r"--([\w]+)=([^ ^=]+)",command_string)
for x in key_args:
cmd_dict[x[0]] = x[1]
self.function_dict[command_root](kwargs=cmd_dict)
this is an extremely simple way (through the use of first-class functions) to build arguments for functions through a generic interface. I will clarify the part about first-class functions (self.function_dict) in my next post.
blog->previouspost = currentpost;
blog->previouspost = currentpost;
No comments:
Post a Comment