[Python-ideas] generic Ref class

Aaron Brady castironpi at comcast.net
Sat Jan 12 21:28:37 CET 2008


> -----Original Message-----
> From: Aaron Brady [mailto:castironpi at comcast.net]
> Sent: Saturday, January 12, 2008 2:26 PM
> To: 'python-ideas at python.org'
> Subject: RE: [Python-ideas] generic Ref class
> 
> > -----Original Message-----
> > From: python-ideas-bounces at python.org [mailto:python-ideas-
> > bounces at python.org] On Behalf Of Aaron Brady
> >
> > > -----Original Message-----
> > > From: python-ideas-bounces+castironpi=comcast.net at python.org
> > > [mailto:python-ideas-bounces+castironpi=comcast.net at python.org] On
> > Behalf
> > > Of Adam Atlas
> > >
> > > On 12 Jan 2008, at 15:03, Aaron Brady wrote:
> > > > Then:
> > > >
> > > > 	for x in refs( listA ):
> > > > 		x.val+= 1
> > > >
> > > > Better than:
> > > >
> > > > 	for i, x in enumerate( listA ):
> > > > 		listA[i]= x+ 1
> > >
> > > Don't these do different things? The latter modifies the original
> > > list, while the former, with your Ref class, apparently modifies (in a
> > > by-reference sense) a new list that is thrown away once the for loop
> > > is done.
> >
> > Ah yes.  Say:
> >
> > 	listA= refs( range( 20 ) ) #or your list
> >
> > then:
> >
> > 	for x in listA:
> > 		x.val+= 1
> >
> > Slightly slower, but useful in addition to pass to functions too:
> >
> > 	def squareanint( intref ):
> > 		intref.val**= 2
> >
> > 	a= 2
> > 	squareanint( a )
> > 	print a
> 
> And once again, I typo:
> 
>  	a= 2
>  	squareanint( Ref( a ) )
>  	print a

Sadly, no good.

	def squareanint( intref ):
		intref.val**= 2
	a= Ref( 3 )
	squareanint( a )
	assert a.val== 9

Like I said, bulky but very handy some times.  It's in -my- library...




More information about the Python-ideas mailing list