Welcome, guest | Sign In | My Account | Store | Cart

useful for decorating functions/methods that you'd like to disable from the main loop or commandline via optparse. an example would be running certain verifications or checks that you deem unnecessary in certain scenarios

Python, 81 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import logging

log = logging.getLogger('decorators') # or whatever you want

class UnhandledSuppression(Exception):
    '''
    this is strictly for handling situations where your
    potentially-suppressed function returns a value.
    if the function is suppressed, variable = suppressedFunc(somevars)
    would contain an invalid value, which could screw up your code.
    so this is thrown, intended to be caught and handled
    '''
    pass

def suppressable(fn):
    decoratorobj = _Suppressable(fn)
    def wrapper(*args, **kwargs):
        return decoratorobj(*args, **kwargs)
    return wrapper
    
class _Suppressable(object):
    '''
    useful in tandem with optparse to parse options and
    suppress certain checks based on command-line variables
    '''
    __suppress = False
    def __init__(self, fn):
        self.fn = fn
        
    def __call__(self, *args, **kwargs):
        '''the actual decorator'''
        if _Suppressable.__suppress:
            log.debug('skipping %s' % repr(self.fn.__name__))
            raise UnhandledSuppression
        else: return self.fn(*args, **kwargs)
    @classmethod
    def suppress(cls, expr):
        cls.__suppress = expr

## EXAMPLE
#from optparse import OptionParser

#usage = 'usage: %prog [options]'
#version = '%prog 0.1'
#parser = OptionParser(usage, version=version)

#parser.add_option('-s', '--suppress', action='store_true', dest='suppress', default=False, help='suppress certain checks')

#options, args = parser.parse_args()
#Suppressable.suppress(options.suppress)

#class SomeProcedure(object):
    #def __init__(self):
        #pass
        
    #def run(self):
        #try: self.doCheck1()
        #except: pass
        
        #try:
            #if self.doCheck2() is False:
                #return
        #except: pass
        
        #self.__actuallyRun()
        
    #def __actuallyRun(self):
        #pass
    
    #@suppressable
    #def doCheck1(self):
        #pass
    
    #@suppressable
    #def doCheck2(self):
        #return False
    
#procedure = SomeProcedure()

## skips checks if the user specified supression
#procedure.run()

it's a very simple recipe but incredibly useful for controlling verifications or different checks. can also be tuned to do a lot more. example above

Created by Andrew Moffat on Sat, 10 Feb 2007 (PSF)
Python recipes (4591)
Andrew Moffat's recipes (6)

Required Modules

Other Information and Tasks