Difference between revisions of "Python/ManyArgs"
From ProgrammingExamples
< Python
(add the page) |
m (add back links) |
||
Line 1: | Line 1: | ||
− | + | [[Python|<font size='-2'>''back to Python examples''</font>]] | |
+ | ---- | ||
+ | Programmers spend much programming time doing maintenance on existing code. This snippet shows one way to handle a function that just keeps growing (without refactoring the code that uses it) in a nice flexible way | ||
<pre> | <pre> | ||
import datetime | import datetime | ||
Line 42: | Line 44: | ||
</pre> | </pre> | ||
+ | [[Python|<font size='-2'>''back to Python examples''</font>]] |
Revision as of 02:00, 27 June 2010
Programmers spend much programming time doing maintenance on existing code. This snippet shows one way to handle a function that just keeps growing (without refactoring the code that uses it) in a nice flexible way
import datetime """ How to easily deal with many parameters in maintenance The problem: - a function has grown to require many parameters, many with default values - the function is being maintained (and param list likely will grow) The forces: - we want the defaults to be seen "all in one place" for self documentation - we may need to handle old positional parameters, also self documented - we want to allow the defaults to be defined outside the function def - we want speed and clarity The answer: Use a dictionary of defaults """ def handleManyArgs(root,logdir,auths,**kwargs): # handle old positional parameters: Historic artifact # opportunity to spell the names nicely, self-document meaning kwargs["rootDirectory"] = root kwargs['logDirectory'] = logdir kwargs['authorizedUsers'] = auths # this dictionary will probably be from a configuration file or similar defaultArgs = { 'alpha': 0, # document this parameter 'beta': 'usually', # ditto 'gamma': 'ray', # ditto 'delta': 12, # etc 'epsilon': 1.03e-12, 'zeta': None, 'eta': datetime.time(hour=11,minute=12,second=13), 'theta': None, 'etc': 'many more', } for k,v in defaultArgs.items(): kwargs.setdefault(k,v) print "All arguments:\n %s"%("\n ".join(["%s->%s"%(str(k),str(v)) for k,v in kwargs.items()])) if __name__ == "__main__": handleManyArgs("/","/tmp",['griswolf']) handleManyArgs("/","/tmp",['griswolf','daviddoria'],gamma='mary',theta=1.35)