Iterators. Iterators. Iterators.
Update (2008-02-11): Kurt Schwehr is thinking about Python code quality too.
Stalking "Python GIS" with Google's blog search led me today to this:
import arcgisscripting gp = arcgisscripting.create() gp.toolbox = "analysis" # Set the workspace gp.workspace = "c:\\Houston\\CrimeData" # Call ListFeatureClasses fcs = gp.ListFeatureClasses( ) #loop through the feature classes and buffer fcs.reset() fc = fcs.next() while fc: outName = "buffered_" + fc gp.buffer(fc, outName, "500 Feet") fc = fcs.next()
What a joyless way to work with Python. The requirement that programmers call reset() and next() is also a sure recipe for bugs. Ideally, the "enumeration objects" would implement the iterator protocol, and you'd just do this:
>>> gp.workspace = r"c:\Houston\CrimeData" >>> for fc in gp.ListFeatureClasses(): ... outName = "buffered_" + fc ... gp.buffer(fc, outName, "500 Feet")
Better yet, you're not going to need to pass an argument into the enumeration factory, so replace it with a property:
>>> gp.workspace = r"c:\Houston\CrimeData" >>> for fc in gp.featureClasses: ... outName = "buffered_" + fc ... gp.buffer(fc, outName, "500 Feet")
Tight. Of course, I've got plans to do it even better in a future release of WorldMill. Something like:
>>> inws = mill.workspace(r"c:\Houston\CrimeData", "r") >>> outws = mill.workspace(r"c:\temp", "w") >>> for cname, collection in inws.items(): ... outws.add(buffer(collection), "buffered_" + cname)
Windows users: save on slashes by using Python's raw (r) strings as I did above.
Comments
Re: Iterators. Iterators. Iterators.
Author: Sean
There's a lot of code in my blog, something that distinguishes me from the purely punditrous. I've finally added syntax highlighting for the code. Go ahead, bring on the bike shed painting comments.Re: Iterators. Iterators. Iterators.
Author: James Fee
Hmm, code over pictures of thongs. You might be on to something there.Re: raw strings
Author: max
NTish versions of Windows(and so python running on those versions) understand forward slashes, like c:/blah, so no need for raw strings, unless you need to support win9x.Re: Iterators. Iterators. Iterators.
Author: Sean
Python 2.5, at least, still favors "\\" (see os.path.sep) on Windows, as you can see when you do os.path.abspath("c:/temp/x/y/z"). Therefore, I think users will encounter fewer problems if they use the Windows convention in a raw string.