Layer (arcpy.mapping)

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 the ArcMap Layer Properties dialog box and it also provides methods for saving layer files. The Layer function, the ListLayers function and the listLegendItemLayers method on the Legend object all provide ways to reference a Layer object.

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 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 (for example, display properties, field aliases, selection symbology, and so on). The UpdateLayer function allows you to replace all layer properties available in the ArcMap Layer Properties dialog box using a layer (.lyr) file that contains the customizations.

Group layers and other sublayers (for example, 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 value 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 file that is also persisted in memory. If this function is executed 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 a layer file on disk will place a lock on the (.lyr) file. It is good practice to remove the object reference using the Python del command at the end of a script or within a Python 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 a more detailed discussion, parameter information, scenarios, and code samples, please refer to the Updating and fixing data sources with arcpy.mapping help topic.

Depending on the symbology type, a layer's symbology can be modified. There are a limited number of supported symbology types for which properties and methods are available. It is good practice to first test the layer's symbologyType property. If a value of OTHER is returned, then the layer's symbology can't be modified. If the value returned is not OTHER, then the layer's symbology property will return one of the following symbology classes, each with their own unique set of methods and properties: GraduatedColorsSymbology, GraduatedSymbolsSymbology, RasterClassifiedSymbology, and UniqueValuesSymbology.

Time-management operations can be performed for time-enabled layers. Not all layer types support time properties. Therefore, it is good practice to first test if the layer supports time using the supports method. If the layer does support time, then time properties can be accessed from the LayerTime class.

Syntax

Layer (lyr_file_path)
ParameterExplanationData Type
lyr_file_path

A string that includes the full path and file name of an existing layer (.lyr) file.

String

Properties

PropertyExplanationData 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 and 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 and 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 layer'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 and 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 and 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
isBroken
(Read Only)

Returns True if a layer's data source is broken.

Boolean
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
isNetworkAnalystLayer
(Read Only)

Returns True if a layer is an ArcGIS Network Analyst extension layer type.

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
isServiceLayer
(Read Only)

Returns True if a layer is a GIS service layer. GIS services are automated geographic information services that are published and accessed over the web using standard technologies and protocols.

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 modified and written back to the layer. Not all layers support the labelClasses property (for example, raster layers and 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
maxScale
(Read and Write)

Provides the ability to set or get the layer's maximum scale threshold.

Double
minScale
(Read and Write)

Provides the ability to set or get the layer's minimum scale threshold.

Double
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

  • ServiceTypeThe property displaying the type of service. This will only be SDE for ArcSDE layer types.
  • ServerThe name or IP address of the computer where the ArcSDE geodatabase is located.
  • ServiceThe name or port number of the process running on the ArcSDE server.
  • DatabaseThe name of the enterprise RDBMS database. This is not required when using Oracle.
  • UserNameA user account. This will be blank if using operating system authentication.
  • AuthenticationModeGeodatabase or operating system authentication.
  • VersionThe version of the geodatabase to which you are connecting.

Keys for a web service dictionary

  • ServiceTypeProperty displaying the type of service. These include ImageServer, IMS, MapServer, TiledInternetLayer, WMS, and WCS.
  • URLProperty displaying the URL to the service. If the connection to ArcGIS for Server is through a local area network (LAN), this value will be null.
  • ServerProperty displaying the server name. If the connection to ArcGIS for Server is through the Internet (HTTP), this value will be null.
  • UserNameProperty displaying the user name used to access a secured service. If the service is not password protected, this property will be null.
  • ServiceNameIMS service layers only. Property displays the name of the IMS service.
  • WMSNameWMS service layers only. Property displays the text string for the WMS service used for machine-to-machine communication.
  • WMSTitleWMS service layers only. Property displays the description title string for the WMS service.
  • NameWMS service layers only. Property displays the text string for the WMS layer used for machine-to-machine communication.
  • TitleWMS service layers only. Property displays the description title string for the WMS layer.
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 and 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
symbology
(Read Only)

Returns a reference to the layer's symbology class. Each supported layer symbology class has its own unique set of properties. It is best to first determine the layer's symbologyType before attempting to modify the symbology class properties.

Object
symbologyType
(Read Only)

Returns a string that represents the layer's symbology class type. Not all layer symbology class types are supported; for those that are not, the keyword OTHER is returned. The following is a list of possible values:

Object
time
(Read Only)

Returns the LayerTime class that provides access to time properties of time-enabled layers.

Object
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 percent usually results in the layer not being drawn at all. Not all layers support the transparency property (for example, fabric group layers and 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

MethodExplanation
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

findAndReplaceWorkspacePath (find_workspace_path, replace_workspace_path, {validate})
ParameterExplanationData 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.

getExtent ({symbolized_extent})
ParameterExplanationData 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
Return Value
Data TypeExplanation
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.

getSelectedExtent ({symbolized_extent})
ParameterExplanationData 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
Return Value
Data TypeExplanation
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.

replaceDataSource (workspace_path, workspace_type, {dataset_name}, {validate})
ParameterExplanationData 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.

  • ACCESS_WORKSPACE A personal geodatabase or Access workspace
  • ARCINFO_WORKSPACE An ArcInfo coverage workspace
  • CAD_WORKSPACEA CAD file workspace
  • EXCEL_WORKSPACEAn Excel file workspace
  • FILEGDB_WORKSPACEA file geodatabase workspace
  • NONEUsed to skip the parameter
  • OLEDB_WORKSPACEAn OLE database workspace
  • PCCOVERAGE_WORKSPACEA PC ARC/INFO Coverage workspace
  • RASTER_WORKSPACEA raster workspace
  • SDE_WORKSPACEAn SDE geodatabase workspace
  • SHAPEFILE_WORKSPACEA shapefile workspace
  • TEXT_WORKSPACEA text file workspace
  • TIN_WORKSPACEA TIN workspace
  • VPF_WORKSPACEA VPF workspace
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.

save ()

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.

saveACopy (file_name, {version})
ParameterExplanationData 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. The default value will use the current version.

  • 10.1Version 10.1/10.2
  • 10.0Version 10.0
  • 8.3Version 8.3
  • 9.0Version 9.0/9.1
  • 9.2Version 9.2
  • 9.3Version 9.3

(The default value is None)

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.

supports (layer_property)
ParameterExplanationData Type
layer_property

The name of a particular layer property that will be tested.

  • BRIGHTNESSA raster layer's brightness value
  • CONTRASTA raster layer's contrast value
  • DATASETNAMEA layers dataset name the way it appears in the workspace
  • DATASOURCEA layer's file path or connection file
  • DEFINITIONQUERYA layer's definition query string
  • DESCRIPTIONA layer's description string
  • LABELCLASSESA layer's list of label classes
  • LONGNAMEA layer's path including the group layer(s) it may be nested within
  • NAMEA layer's name
  • SERVICEPROPERTIESConnection information for SDE and web service layers
  • SHOWLABELSA Boolean indicating if a layer's lables are toggled on or off
  • SYMBOLOGYA layer's symbology class
  • SYMBOLOGYTYPEA layer's symbology class type
  • TIMEA layer's time properties
  • TRANSPARENCYA layer's transparency value
  • VISIBLEA Boolean indicating if a layer is toggled on or off in the TOC
  • WORKSPACEPATHA layer's workspace or connection file path

(The default value is name)

String
Return Value
Data TypeExplanation
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

Layer example 1

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
Layer example 2

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, 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
Layer example 3

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('Service', '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
Layer example 4

The following script modifies the symbology for a layer in a map document. It first updates the layer's symbology using a layer file on disk with the UpdateLayer function. The layer file contains a custom color ramp that is applied to the layer. Next, it verifies that the layer has graduated color symbology. Finally, the script modifies a number of the properties on the GraduatedColors symbology class and exports the result to PDF.

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "Census")[0]
lyr = arcpy.mapping.ListLayers(mxd, "StatePopulation", df)[0]
lyrFile = arcpy.mapping.Layer(r"C:\Project\LYRs\Population.lyr")
arcpy.mapping.UpdateLayer(df, lyr, lyrFile, True)
if lyr.symbologyType == "GRADUATED_COLORS":
  lyr.symbology.valueField = "POP2000"
  lyr.symbology.numClasses = 4
  lyr.symbology.classBreakValues = [250000, 999999, 4999999, 9999999, 35000000]
  lyr.symbology.classBreakLabels = ["250,000 to 999,999", "1,000,000 to 4,999,999", 
                                    "5,000,000 to 9,999,999", "10,000,000 to 35,000,000"]
arcpy.mapping.ExportToPDF(mxd, r"C:\Project\Output\StatePopulation.pdf")
del mxd, lyrFile
Layer example 5

The following script tests if a layer file supports time and if time properties have been set. It then uses time information (start time and end time) to calculate the time extent of a time-enabled layer.

import arcpy, datetime
lyr = arcpy.mapping.Layer(r'C:\Project\Data\Time\TemperatureWithTime.lyr')
if lyr.supports("TIME"):
    lyrTime = lyr.time
    if lyr.time.isTimeEnabled:
        startTime = lyrTime.startTime
        endTime = lyrTime.endTime
        timeDelta = endTime - startTime
        print "Start Time: " + str(startTime)
        print "End Time: " + str(endTime)
        print "Time Extent: " + str(timeDelta)
    else:
        print "No time properties have been set on the layer"
else:
    print "Time is not supported on this layer"
3/3/2014