Trainer Eric Pimpler shares his list of the ten most common Python errors. The list may be particularly valuable to beginner level Python programmers working with ArcGIS, but more experienced coders might find some valuable reminders.
Over the years I have taught hundreds of beginning level Python programmers how to automate their ArcGIS geoprocessing tasks. Needless to say I have seen all sorts of errors. But there are some common errors that I see over and over again. So if you’re a beginner level Python programmer working with ArcGIS hopefully this will help get you over the hump. Below you will find my list of the 10 most common errors in no particular order.
1. Typos – This should probably go without even saying but typos are the most common and consistent mistake. When you get an error in your code this should probably be the first thing you check. Make sure that when you reference a variable somewhere in your code that the variable name you’re referring to is spelled exactly as you defined the variable name earlier. Here’s an example:
layerParcel = “Streets”
if lyerParcel == “Streets”: #notice that I left out the ‘a’ in layerParcel
2. Python is case sensitive – This is probably the most common non-typo error that I run across when teaching Python to beginning level programmers. This means for example that the Python interpreter will see the following as completely different variables.
mapsize = “34x44”
MapSize = “22x32”
It’s not uncommon to see new programmers define a variable with an alternate mix of casing (MapSize) but then later attempt to refer to the variable using a different mixture of case (mapsize) which results in an error.
3. Indentation – Python makes extensive use of indentation. Python functions have no explicit begin or end, and no curly braces to mark where the function code starts and stops. The only delimiter is a colon (:) and the indentation of the code itself. See the example below:
import arcpy.mapping as mapping
mxd = mapping.MapDocument(“CURRENT”)
for df in mapping.ListDataFrames(mxd):
for lyr in mapping.ListLayers(mxd, “”, df)
if lyr.name == “School Districts”:
Code blocks are defined by their indentation. By “code block”, I mean functions, if statements, for loops, while loops, and so forth. Indenting starts a block and un-indenting ends it. There are no explicit braces, brackets, or keywords. This means that whitespace in this case is significant (usually it’s not in Python but when it comes to indentation for code blocks it is), and must be consistent. You don’t have to include any particular number of spaces, it just needs to be consistent.
You should also avoid mixing tabs and spaces in the indentation of a given single block. Otherwise, what you see in your editor may not be what Python sees when it counts tabs as a number of spaces. It’s safer to use all tabs or all spaces for each block. The number of spaces is up to you.
4. Remember to include the colons for compound statements – This is a very common beginner’s coding mistake: don’t forget to type a : at the end of compound statement headers (the first line of an if, while, for, try, with). I would say that a majority of my students make this mistake at least once and usually many times throughout training. I think this is partly because they simply don’t have a full understanding of what that colon represents which is that it defines the beginning of a code block.
5. Variable names should begin with a letter or underscore – Variables should begin with a letter or an underscore. Don’t begin a variable name with a number or any other special character. Also, there are certain words that are reserved and can’t be used as variable names including the following:
and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise , return, try, while, yield
6. Initialize Your Variables - In Python, you cannot use a variable name within an expression until it has been assigned a value. This is on purpose: it helps to prevent common typo mistakes, and avoids the ambiguous question of what an automatic default should be (0, None, “”, , ?). Remember to initialize counters to 0, list accumulators to , and so on.
7. Automatic extensions in windows – If you’re coding in something really basic like Notepad make sure you explicitly give your file a .py suffix when saving. Otherwise, your file will be saved with a .txt extension, making it difficult to run in some launching schemes. MS Word and Wordpad also add formatting characters by default that are not legal Python syntax. You should always pick All Files when saving and and save as simple text on Windows, or use more programmer friendly editors such as IDLE. However, if you’re using IDLE there is a gotcha with this editor as well. You have to remember to type the .py file extension when saving. For some reason it won’t automatically add the .py extension.
8. More indentation rules – Be sure to start top-level, un-nested code all the way to the left. There shouldn’t be any space to the left of the first line of code. Not even one space. As I mentioned above, Python uses indentation to delimit blocks of nested code, so white space to the left of your code means a nested block. White space is generally ignored everywhere, except for indentation. I have seen students add a single space to top-level un-nested code more times than I can count. I’m not sure why that is the case but it happens.
9. Use parentheses to call a function – You must add parentheses after a function name to call it, whether it takes arguments or not. A proper function call would be append() not append. Even though append() in this case doesn’t need any parameters to execute you do need to include the parentheses to execute the function.
10. Don’t use a single backslash when referencing paths to datasets – A single backslash in Python is an escape character. For example Python sees \n as a line feed and \t as a tab. Therefore, representing a path to a dataset as c:\data\myshapefile.shp will result in an error. You have several choices to resolve this. The easiest way to handle this problem is to include a lowercase ‘r’ before the path as in r”c:\data\myshapefile.shp”. You could also use two backslashes “c:\\data\\myshapefile.shp” or a single forward slash “c:/data/myshapefile.shp”.
Want to learn more about how to use Python to automate your geoprocessing tasks? Check out our [Geospatial Training Services'] upcoming Programming ArcGIS with Python Workshops.
Reprinted with permission from GeoChalkboard, A GeoSpatial Training Services Blog.