Layer
Summary
Provides access to layer properties and methods. It can either reference layers in a map document (.mxd) or layers in a layer (.lyr) file.
Discussion
The Layer object is essential for managing layers that reside within a map document (mxd) or within a layer (lyr) file. The layer object provides access to many of the common layer properties found in ArcMap's Layer Properties dialog box and it also provides methods for saving layer files. In addition to the Layer constructor function, the ListLayers function also provides the ability to get a reference to a Layer object. The ListLayers function is ideal for finding and referencing specific layers in a map document or layer file.
There are numerous types of layers and not all of them support the same set of properties. For example, a feature layer supports a definition query whereas a raster layer does not, but a raster catalog does. Rather than having to work with different, individual layer objects for all possible layer types and property combinations, a supports method is available to help identify which layer types support which individual layer properties. The supports method gives you the ability to test if the layer supports a property before trying to get or set its value on a layer type that doesn't support it, therefore reducing the need for additional error trapping.
There are essentially three categories of layers in a map document: feature layers, group layers, and raster layers. The isFeatureLayer, isGroupLayer, and isRasterLayer properties that work with the supports method allow you to identify or isolate the majority of layer types but not all layer types. There are a few specialized layers and datasets that don't fall into one of these three categories: annotation subclasses, dimension features, network datasets, terrain datasets, topology datasets, and so on. In these cases you may need to test other properties to isolate a layer of interest before doing something to it.
Not all layer properties are accessible through the Layer object. There are many properties available in the ArcMap Layer Properties dialog box that are not exposed to the arcpy scripting environment (e.g., scale ranges, display properties, field aliases, symbology, and so on). The UpdateLayer function allows you to replace all layer properties available in ArcMap's Layer Properties dialog box using a layer (.lyr) file that contains the customizations.
Group layers and other sublayers (e.g., annotation classes) are treated just like ordinary layers. The ListLayers function returns index values that are generated from top to bottom as they appear in the table of contents or the way they appear in a layer (.lyr) file. The same applies if a group layer is within another group layer. For example, a map document with a single group layer that contains three sublayers will return a list of four layer names, the group layer being the first and the three sublayers being the second, third, and fourth. There are two ways of determining if a layer is a group layer. First you can check to see if the layer supports the isGroupLayer property. Second, you can evaluate the longNameproperty. A layer's longName will include the group name in addition to the layer name. For example, a layer named Layer1 in a group layer named Group1 will have a longNamevalue of Group1\Layer1. If the name value is equal to longName value, then the layer is not a group layer or the layer is not inside a group layer.
Some layers within a map document or layer file may be password protected because the user and password information is not saved within the layer file or map document. Map documents that contain these layers will prompt the user to enter the appropriate information while the document is opening. The arcpy.mapping scripting environment will, by default, suppress these dialog boxes during execution but that means that the layers will be treated as though they have broken data sources. In other words, secured layers will not be rendered in any output. If it is necessary for these layers to render appropriately, then there are a couple of options. First, save the user name and password information with the layers. Second, the CreateArcSDEConnectionFile geoprocessing function allows you to create a connection that is persisted in memory. If this command is used prior to opening a map document (.mxd) with the MapDocument function or a layer file with the Layer function, then SDE layers will render. Currently, there is no alternative for secured web services.
The variable that references the MapDocument object will place a lock on the (.mxd) file. It is good practice to remove the object reference using the Python del command at the end of a script or within a try/except statement.
Changing a layer's data source is a common requirement. There are two methods on the Layer object that help with this. The findAndReplaceWorkspacePath method is intended for replacing part or all of a layer's workspace path. The replaceDataSource method allows you to change a layer's workspace and source dataset. For more detailed discussion, parameter information, scenarios, and code samples, please refer to the Updating and fixing data sources with arcpy.mapping help topic.
Syntax
Parameter | Explanation | Data Type |
lyr_file_path |
A string that includes the full path and file name of an existing layer (.lyr) file. | String |
Properties
Property | Explanation | Data Type |
brightness (Read and Write) |
Provides the ability to get or set the brightness value. The default, normal brightness, is 0%. Enter any value between +100% and -100%. Enter a plus or minus sign to the left of the value to specify whether it is above or below 0. Not all layers support the brightness property (for example, group layers, feature layers), so it is good practice to test for this ahead of time using the supports method. | Integer |
contrast (Read and Write) |
Provides the ability to get or set the contrast value. The default, neutral contrast, is 0%. Enter any value between +100% and -100%. Enter a plus or minus sign to the left of the value to specify whether it is above or below 0. Not all layers support the contrast property (for example, annotation layers, fabric layers), so it is good practice to test for this ahead of time using the supports method. | Integer |
credits (Read and Write) |
Provides the ability to either get or set the map document's credits or copyright information. | String |
datasetName (Read Only) |
Returns the name of the layer's dataset the way it appears in the workspace, not in the TOC. Not all layers support the datasetName property (for example, Web services), so it is good practice to test for this ahead of time using the supports method. | String |
dataSource (Read Only) |
Returns the complete path for the layer's data source. It includes the workspacePath and the datasetName properties combined. Not all layers support the dataSource property (for example, annotation classes, Web services), so it is good practice to test for this ahead of time using the supports method. | String |
definitionQuery (Read and Write) |
Provides the ability to get or set a layer's definition query. Not all layers support the definitionQuery property (for example, raster layers, group layers), so it is good practice to test for this ahead of time using the supports method. | String |
description (Read and Write) |
Provides the ability to either get or set the layer's description information. Not all layers support the description property (for example, topology layers), so it is good practice to test for this ahead of time using the supports method. | String |
isFeatureLayer (Read Only) | Returns True if a layer is a feature layer. | Boolean |
isGroupLayer (Read Only) | Returns True if a layer is a group layer. | Boolean |
isRasterizingLayer (Read Only) | Returns True if a layer will cause rasterization of other vector layers in the data frame when the map is printed or exported. Rasterization of vector layers during output most often occurs when layer transparency is used but can also happen when a layer has raster-based picture symbols or field-based transparency. | Boolean |
isRasterLayer (Read Only) | Returns True if a layer is a raster layer. | Boolean |
labelClasses (Read and Write) |
Provides access to a layer's label class properties by returning a list of LabelClass objects. Individual LabelClass object properties can be read and/or modified and written back to the layer. Not all layers support the labelClasses property (for example, raster layers, annotation layers), so it is good practice to test for this ahead of time using the supports method. | LabelClass |
longName (Read Only) |
This property is valuable when trying to determine whether a layer belongs to a group layer. If a layer does not belong to a group layer, the long name will equal the layer name. If a layer does belong to a group layer, the group layer structure will be included in the long name. For example, the name of a layer nested inside a group layer within another group layer may look something like Group1\Group2\LayerName. All layer types support this property. | String |
name (Read and Write) |
Provides the ability to set or get the name of a layer the way it would appear in the ArcMap table of contents. Spaces can be included. All layer types support this property. | String |
serviceProperties (Read Only) |
Provides access to connection information for ArcSDE and Web service layers. The returned results are dictionary key-value pairs. There are two different dictionaries returned based on the type of layer. The first is for ArcSDE connections, and the second is for all Web service layer types. The Web services dictionary contains keys that work for all service layer types and also includes specific keys that work for only a particular Web service type (for example, WMS has a key called WMSTitle). Either your script can check the ServiceType key before evaluating specific keys or you can use the get method that allows you to bypass keys that are not available. Not all layers support the serviceProperties property (for example, layers that are not ArcSDE or Web service layers), so it is good practice to test for this ahead of time using the supports method. Keys for an ArcSDE dictionary
Keys for a Web service dictionary
| Dictionary |
showLabels (Read and Write) |
Controls the display of labels for a layer. If set to True, labels will display; if set to False, labels will not be drawn. Not all layers support the showLabels property (for example, raster layers, annotation layers), so it is good practice to test for this ahead of time using the supports method. Layer types that support the showLabels property also support the labelClasses property. | Boolean |
transparency (Read and Write) |
Provides the ability to get or set the transparency value. This enables you to "see through" a layer to the layers underneath. Type 0 if you don't want a layer to be transparent. A transparency value of more than 90% usually results in the layer not being drawn at all. Not all layers support the transparency property (for example, fabric group layers, Web service sublayers), so it is good practice to test for this ahead of time using the supports method. | Integer |
visible (Read and Write) |
Controls the display of a layer. This has the same effect as checking the check box next to the layer in the table of contents in ArcMap. If set to True, the layer will draw; if set to False, the layer will not be drawn. Not all layers support the visible property (for example, restricted Web service layers), so it is good practice to test for this ahead of time using the supports method. | Boolean |
workspacePath (Read Only) |
Returns a path to the layer's workspace or connection file. Not all layers support the workspacePath property (for example, Web services), so it is good practice to test for this ahead of time using the supports method. | String |
Method Overview
Method | Explanation |
findAndReplaceWorkspacePath (find_workspace_path, replace_workspace_path, {validate}) |
Finds and replaces a layer's workspace path with a new workspace path. |
getExtent ({symbolized_extent}) |
Returns a layer's geometric or symbolized extent. |
getSelectedExtent ({symbolized_extent}) |
Returns a layer's geometric or symbolized extent for selected features. |
replaceDataSource (workspace_path, workspace_type, {dataset_name}, {validate}) |
Replaces a data source for a layer in a map document (.mxd) or layer (.lyr) file. It also provides the ability to switch workspace types (e.g., replaces a file geodatabase data source with an SDE data source). |
save () |
Saves a layer (.lyr) file. |
saveACopy (file_name, {version}) |
Saves a layer (.lyr) file to a different file name and, optionally, a previous version. |
supports (layer_property) |
Not all layers support the same set of properties. The supports property can be used to test which properties a layer does support. |
Methods
Parameter | Explanation | Data Type |
find_workspace_path |
A string that represents the workspace path or connection file you want to find. If an empty string is passed, then all workspace paths will be replaced with the replace_workspace_path parameter depending on the value of the validate parameter. | String |
replace_workspace_path |
A string that represents the workspace path or connection file you want to replace. | String |
validate | If set to True, the workspace will only be updated if the replace_workspace_path value is a valid workspace. If it is not valid, the workspace will not be replaced. If set to False, the method will set the workspace to match the replace_workspace_path, regardless of a valid match. In this case, if a match does not exist, then the layer's data source would be broken. (The default value is True) | Boolean |
For more detailed discussion, parameter information, scenarios, and code samples, please refer to the Updating and fixing data sources with arcpy.mapping help topic.
Parameter | Explanation | Data Type |
symbolized_extent |
A value of True will return the layer's symbolized extent; otherwise, it will return the geometric extent. The symbolized extent takes into account the area the symbology covers so that it does not get cut off by the data frame's boundary. (The default value is True) | Boolean |
Data Type | Explanation |
Extent |
The getExtent method will honor a layer's definition query so if a subset of features are queried, getExtent will return the extent for only those features.
A symbolized extent takes into account the area of the feature's symbol when building the extent rectangle. Returning a symbolized extent may be best for cartographic results because symbols won't be cut off at the data frame's edges. A geometric extent may be best for analysis.
Parameter | Explanation | Data Type |
symbolized_extent |
A value of True will return the layer's symbolized extent; otherwise, it will return the geometric extent. The symbolized extent takes into account the area the symbology covers so that it does not get cut off by the data frame's boundary. (The default value is True) | Boolean |
Data Type | Explanation |
Extent |
A symbolized extent takes into account the area of the feature's symbol when building the extent rectangle. Returning a symbolized extent may be best for cartographic results because symbols won't be cut off at the data frame's edges. A geometric extent may be best for analysis.
Parameter | Explanation | Data Type |
workspace_path |
A string that includes the workspace path to the new data or connection file. | String |
workspace_type | A string keyword that represents the workspace type of the new data.
| String |
dataset_name | A string that represents the name of the dataset the way it appears in the new workspace (not the name of the layer in the TOC). If dataset_name is not provided, the replaceDataSource method will attempt to replace the dataset by finding a table with a the same name as the layer's current dataset property. | String |
validate | If set to True, a workspace will only be updated if the workspace_path value is a valid workspace. If it is not valid, the workspace will not be replaced. If set to False, the method will set the source to match the workspace_path, regardless of a valid match. In this case, if a match does not exist, then the data source would be broken. (The default value is True) | Boolean |
For more detailed discussion, parameter information, scenarios, and code samples, please refer to the Updating and fixing data sources with arcpy.mapping help topic.
There is a subtle difference between a layer (.lyr) file and a map layer (a layer in a map document). The save method only works when a variable references a layer file and will not work with a map layer. When a layer is loaded from a layer file it will remember the file name and use that when the save method is called. If a map layer is being referenced, a file name is not initially set, so you will need to use the saveACopy method instead.
Parameter | Explanation | Data Type |
file_name |
A string that includes the location and name of the output layer (.lyr) file. | String |
version |
A string that sets the output version number. If a value is not used, the current version is used.
(The default value is 10.0) | String |
Provides an option to save a layer (.lyr) file to a different file name and, optionally, a previous version. Features that are not supported in prior versions of the software will be removed from the newly saved layer.
Parameter | Explanation | Data Type |
layer_property |
The name of a particular layer property that will be tested.
(The default value is name) | String |
Data Type | Explanation |
Boolean |
There are numerous types of layers and not all of them support the same properties. For example, a feature layer supports a definition query whereas a raster layer does not, but a raster catalog does. Rather than creating individual layer objects for all possible layer types and property combinations, a support method was created to help identify which layer types support which properties. The support method gives you the option of testing the property before trying to get or set its value on a layer type that doesn't support it. The supports property will return a true if a layer supports that property.
Code Sample
The following script will reference a layer (.lyr) file, find all layers called Highways, turns on labels, and save the results to a new layer file.
import arcpy lyrFile = arcpy.mapping.Layer(r"C:\Project\Data\Streets.lyr") for lyr in arcpy.mapping.ListLayers(lyrFile): if lyr.name.lower() == "highways": lyr.showLabels = True lyr.saveACopy(r"C:\Project\Data\StreetsWithLabels.lyr") del lyrFile #Or with one less line using a wild card: import arcpy lyrFile = arcpy.mapping.Layer(r"C:\Project\Data\Streets.lyr") for lyr in arcpy.mapping.ListLayers(lyrFile, "Highways"): lyr.showLabels = True lyr.saveACopy(r"C:\Project\Data\StreetsWithLabels.lyr") del lyrFile
The following script will allow secured layers to render correctly by creating an SDE connection in memory before opening a map document that requires password information. This script simply defines the connection information and then exports the map document to a PDF file. It is good practice to delete this reference from memory before the script closes.
import arcpy, os #Remove temporary connection file if it already exists sdeFile = r"C:\Project\Output\TempSDEConnectionFile.sde" if os.path.exists(sdeFile): os.remove(sdeFile) #Create temporary connection file in memory arcpy.CreateArcSDEConnectionFile_management(r"C:\Project\Output", "TempConnection", "myServerName", "5151", "myDatabase", "DATABASE_AUTH", "myUserName", "myPassword", "SAVE_USERNAME", "myUser.DEFAULT", "SAVE_VERSION") #Export a map document to verify that secured layers are present mxd = arcpy.mapping.MapDocument(r"C:\Project\SDEdata.mxd") arcpy.mapping.ExportToPDF(mxd, r"C:\Project\output\SDEdata.pdf") os.remove(sdeFile) del mxd
The following script will print the name of each SDE or web service layer along with the appropriate service information. Similar to the example above, since some SDE layers may be secured with password information, a temporary SDE connection file is created. This example does not print information about non-SDE or web service layers.
import arcpy, os #Remove temporary connection file if it already exists sdeFile = r"C:\Project\Output\TempSDEConnectionFile.sde" if os.path.exists(sdeFile): os.remove(sdeFile) #Create temporary connection file in memory arcpy.CreateArcSDEConnectionFile_management(r"C:\Project\Output", "TempConnection", "myServerName", "5151", "myDatabase", "DATABASE_AUTH", "myUserName", "myPassword", "SAVE_USERNAME", "myUser.DEFAULT", "SAVE_VERSION") #Report service properties for layers in a map that support SERVICEPROPERTIES mxd = arcpy.mapping.MapDocument(r"C:\Project\ServerData.mxd") for lyr in arcpy.mapping.ListLayers(mxd): if lyr.supports("SERVICEPROPERTIES"): servProp = lyr.serviceProperties print "Layer name:" + lyr.name print "-----------------------------------------------------" if lyr.serviceProperties["ServiceType"] != "SDE": print "Service Type: " + servProp.get('ServiceType', 'N/A') print " URL: " + servProp.get('URL', 'N/A') print " Connection: " + servProp.get('Connection', 'N/A') print " Server: " + servProp.get('Server', 'N/A') print " Cache: " + str(servProp.get('Cache', 'N/A')) print " User Name: " + servProp.get('UserName', 'N/A') print " Password: " + servProp.get('Password', 'N/A') print "" else: print "Service Type: " + servProp.get('ServiceType', 'N/A') print " Database: " + servProp.get('Database', 'N/A') print " Server: " + servProp.get('Server', 'N/A') print " Service: " + servProp.get('Instance', 'N/A') print " Version: " + servProp.get('Version', 'N/A') print " User name: " + servProp.get('UserName', 'N/A') print " Authentication: " + servProp.get('AuthenticationMode', 'N/A') print "" del mxd