Package cliutils :: Module decorators
[hide private]
[frames] | no frames]

Module decorators

source code

Functions [hide private]
 
decorator(callable)
Simple meta-decorator that makes decorators preserve the attributes of the modified function.
source code
 
cliargs(f)
Decorator that parses sys.argv and passes the results into the function.
source code
 
logged(fobj)
Factory for a decorator that redirects sys.stdout to a given file-like object during function execution.
source code
 
log_decorator(fobj)
Create a logged decorator for re-use.
source code
 
indir(newdir)
Factory for decorator that ensures the decorated function is run in a specified directory, then changes back to original directory.
source code
Function Details [hide private]

decorator(callable)

source code 

Simple meta-decorator that makes decorators preserve the attributes of the modified function.

Stolen from innumerable online recipes, but most directly from http://wiki.python.org/moin/PythonDecoratorLibrary.

cliargs(f)

source code 

Decorator that parses sys.argv and passes the results into the function.

Meant for functions that are a target of setuptools' automatic script creation (by default, nothing is passed in, and the function must handle sys.argv parsing itself). If something very simple is all that is required, this is the answer. Fancier arguments should use getopt or optparse.

If the wrong args/kwargs are passed in such that a TypeError is raised, the docstring is printed, so that's an ideal place to put usage information.

Decorators:
  • @decorator

logged(fobj)

source code 

Factory for a decorator that redirects sys.stdout to a given file-like object during function execution. Thus, print statements can become logged statements.

log_decorator(fobj)

source code 

Create a logged decorator for re-use.

>>> from StringIO import StringIO
>>> logfile = StringIO()
>>> logger = log_decorator(logfile)
>>> @logger
... def func():
...     print "ABCDEFGHIJK"
... 
>>> func()
>>> logfile.seek(0)
>>> logfile.read().strip()
'ABCDEFGHIJK'

indir(newdir)

source code 

Factory for decorator that ensures the decorated function is run in a specified directory, then changes back to original directory.

>>> import tempfile
>>> realpath = os.path.realpath
>>> new, cur = map(realpath, (tempfile.mkdtemp(), os.curdir))
>>> @indir(new)
... def whereami():
...     return realpath(os.curdir)
...
>>> whereami() == new
True
>>> realpath(os.curdir) == cur
True