Not celebrating the holidays does give me something: free time during break.
I've been tinkering with a whole bunch of different things leisurely during my break thus far. Before leaving, I had attended RIT's STEM Challenge hackathon (didn't end up working on a STEM game, though) and decided with my buddy Logan Mitchell that we'd try porting a MUD engine I had written some time ago in Java to Python, and make it better. It would be a good side-project to learn some things about the language.
One of the notable cool things I picked up was a nice way of generating the common "help files" for commands in the MUD, in a way that allows allowed us to document these commands at the same time. I had an idea. What if we could use the function docstring, and through reflection, generate a helpfile from it? Turns out, python can make that happen pretty easily. Inside our commands.py module...
import sys
import inspect
...
def help(args):
"""
Check the helpfiles for something.
syntax: help <subject>
subject - the subject or command which you want to check for help on
"""
...
# args is a namedtuple
helpFunctionName = args.tokens[1]
# use reflection to get a list of this module's function object
functions = inspect.getmembers(sys.modules[__name__], inspect.isfunction)
for functionName, function in functions:
if functionName == helpFunctionName:
docstring = function.__doc__
prelude = "help file for: " + args.tokens[1] + "\n"
dashline = ("-"*len(prelude))
return prelude + dashline + docstring
So, calling "help help" in our MUD will actually pull out help's docstring and have it contribute to the help file. Pretty cool stuff.
No comments:
Post a Comment