Confused with csv.reader copies

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Jul 23 17:38:37 EDT 2007


En Mon, 23 Jul 2007 15:45:42 -0300, Robert Dailey <rcdailey at gmail.com>  
escribió:

> import csv
>
> def pass1( reader ):
> 	print reader.next()
> 	print reader.next()
>
> def pass2( reader ):
> 	print reader.next()
> 	print reader.next()
>
> reader = csv.reader( open( "C:/IT/Method/SpaceImpact/code/tools/
> ProfileViewer/performance_profile.csv", "rb" ) )
>
> pass1( reader )
> pass2( reader )

[expecting the two calls to print the same two lines]

> My understanding is that objects are passed by reference, meaning
> there is no hard copy of the data, however the copies passed to
> functions do not affect the version passed in. In other words, when I
> call "next" on the reference passed into each function, it should not
> affect the variable that was originally passed in.

Both functions receive the *same* reader object, not a copy. Calling  
next() affects the reader internal state, it doesn't matter where you call  
it from.
You should read this threads from last week:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/45732106f147ac07/
http://groups.google.com/group/comp.lang.python/browse_thread/thread/56e7d62bf66a435c/

> I'm attempting to use recursion to build a TreeCtrl in wxPython using
> this data, and I can't get it to work properly if the variable outside
> of the function call ends up having its state (e.g., its "next"
> pointer) modified by passing it into other functions.
>
> Any tips on getting this to work? I'm a native C++ programmer still
> learning Python, so I apologize for any confusion. Thanks.

The simplest way -if the file is not so huge- is to read the whole file  
and keep the results in a list: lines = list(reader)
There are other alternatives using the itertools module but aren't easy to  
grasp for a beginner.

-- 
Gabriel Genellina




More information about the Python-list mailing list