mutable default parameter problem [Prothon]

Pierre-Frédéric Caillaud peufeu at free.fr
Fri Jun 18 10:52:00 CEST 2004



> 2) Evaluate the default expression once at each call time when the  
> default
> value is needed.  The default expression would be evaluated in the  
> context
> of the function definition (like a closure).


	I like Choice 2 because I've always wanted to do the following :

def func( x, y=2*x ):
	do stuff...

	ie. use default values for function parameters which depend on previous
function parameters.
	This can be very practical at times :

	before (suppose 'info' is a class which has "text" and "htmlclass" as
members):

	def format_information( info, htmlclass = None ):
		if htmlclass == None:
			htmlclass = info.htmlclass
		return "<p class=%s>%s</p>" % (htmlclass, info.text )
	
	after:

	def format_information( info, htmlclass = info.htmlcass ):
		return "<p class=%s>%s</p>" % (htmlclass, info.text )


	the intended use would be :
	format_information( info )
	format_information( info, 'red_text' ) overrides the html_class in info.


	The former example could be simplified (below) but I still think the
second example using your choice 2 is more elegant.

	def format_information( info, htmlclass = None ):
		return "<p class=%s>%s</p>" % (htmlclass or info.htmlclass, info.text )
-- 
Using Opera's revolutionary e-mail client: http://www.opera.com/m2/



More information about the Python-list mailing list