[Python-Dev] Enhancement suggestion for module new.py

John McLaughlin John.McLaughlin at reachin.se
Thu Aug 28 16:10:54 EDT 2003


Hi all,

I hope this is the right place to make this type of suggestion.
I put together the following two functions and have found them
very useful. I think they probably belong in the new.py module
along with instancemethod(), code() and function() that they
rely on. Any thoughts?

Cheers,
-John

import new
from types import ClassType

def installmethod( function, object, name = None ):
	"""
	This function adds either a bound method to an instance or
	an unbound method to a class. If name is ommited it defaults
	to the name of the given function.
	Example:
	  a = A()
	  def f( self, x, y ):
	    self.z = x + y
	  installmethod( f, A, "add" )
	  a.add( 2, 4 )
	  print a.z
	  installmethod( lambda self, i: self.l[i], a, "listIndex" )
	  print a.listIndex( 5 )
	"""
	if name == None:
		name = function.func_name
	else:
		function = renamefunction( function, name )
	if type(object) == ClassType:
		setattr( object, name,
				 new.instancemethod( function, None, object
) )
	else:
		setattr( object, name,
				 new.instancemethod( function, object,
object.__class__ ) )

def renamefunction( function, name ):
	"""
	This function returns a function identical to the given one, but
	with the given name.
	"""
	c = function.func_code
	if c.co_name != name:
		# rename the code object.
		c = new.code( c.co_argcount, c.co_nlocals, c.co_stacksize,
					  c.co_flags, c.co_code,
c.co_consts,
					  c.co_names, c.co_varnames,
c.co_filename,
					  name, c.co_firstlineno,
c.co_lnotab )
	if function.func_defaults != None:
		return new.function( c, function.func_globals, name,
	
function.func_defaults )
	return new.function( c, function.func_globals, name )


if __name__ == '__main__':
	# example
	class A:
		def installButton( self, name ):
			def f( self, name=name ):
				print name, 'pressed'
			installmethod( f, self, name )
			
	a = A()
	a.installButton( 'foo' )
	a.foo()
	# A().foo() raises AttributeError
	
	def f( self, x, y ):
		self.z = x + y
	installmethod( f, A, "add" )
	a.add( 2, 4 )
	print a.z
	installmethod( lambda self, i: self.l[i], A, "listIndex" )
	a.l = list( "abc" )
	print a.listIndex( 1 )



More information about the Python-Dev mailing list