call 'the following function' using decorators

castironpi at gmail.com castironpi at gmail.com
Tue Feb 12 12:20:32 EST 2008


I assert it's easier to write:

start_new_thread( this_func )
def thrA():
    normal_suite()

than

def thrA():
    normal_suite()
start_new_thread( thrA )

If you don't, stop reading.  If you do, accomplish it like this:

@decwrap( start_new_thread, Link, ( 2, 3 ) )
def anonfunc( a, b ):
	print( a, b )

where 'Link' replaces the following func, plus in keywords too:

@decwrap( Thread, None, target= Link, args= ( 2, 3 ) )
def sampleth( a, b ):
	print( a, b )
sampleth.start()
sampleth.join()

'Link' is a pseudo-constant.

Link= object()

@decwrap follows.

def decwrap( func, *ar, **kwar ):
	def predec( func2 ):
		ar2= list( ar )
		while Link in ar2:
			ar2[ ar2.index( Link ) ]= func2
		kwar2= kwar.copy()
		for k, v in kwar2.items():
			if v is not Link: continue
			kwar2[ k ]= func2
		ret= func( *ar2, **kwar2 )
		return ret
	return predec

Further applications:

@decwrap( button.bind, "<Key-X>", Link )
def anonfunc():
	print( 'Key X pressed' )

Optional stylism for readability:

@decwrap( start_new_thread, ~Link, ( 2, 3 ) )
@decwrap( Thread, None, target= ~Link, args= ( 2, 3 ) )
@decwrap( button.bind, "<Key-X>", ~Link )

where 'Link' is:

class NegMarking:
	def __invert__( self ): return self

Link= NegMarking()



More information about the Python-list mailing list