Layer

サマリー

Provides access to basic layer properties and methods.

説明

Layers can be referenced from within a project using the listLayers method on the Map class or in a layer file (.lyr or .lyrx) stored on disk using the listLayers method on the LayerFile class.

The Layer object has a single, generic design to work with all layers. 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 the possible layer types and property combinations, there are some useful properties that allow you to obtain information about a layer and its supported properties. There are many is properties that allow you to determine if a layer fits into a general category, for example, is3DLayer, isFeatureLayer, isGroupLayer, isRasterLayer, isWebLayer, and so on.

There are a few specialized layers and datasets that don't fall into one of these general categories: annotation subclasses, dimension features, 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. The supports method is available to help identify which specific layer supports which specific layer property. It gives you the ability to test whether the layer supports a property before trying to get or set its value, reducing the need for additional error trapping. For example, see the following code:


if lyr.supports("BRIGHTNESS"):
    lyr.brightness = 10

The listLayers method on the Map class returns index values that are generated from top to bottom as they appear in the table of contents or as they appear in a layer file. The same applies if a group layer is within another group layer. For example, a map 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 longName property. 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 longName value of Group1\Layer1. If the name value is equal to the longName value, the layer is not inside a group layer. When working with the sublayers of composite layers, the longName property will contain both the sublayer and top-level layer name.

ArcGIS Pro can read legacy .lyr file types, but it can only save to .lyrx file types. If a .lyr file type is being referenced and the save method is called, it will be converted to a .lyrx file type but with the same file name.

A feature layer can support zero to many definition queries, but only one definition query can be active. It is also possible that one or many definition queries are present but none are active. There are a couple of ways to manage definition queries. First, you can use the definitionQuery property. If you set a unique SQL string on a layer that does not have a definition query or a layer that has multiple definition queries, the new definition query is added and it becomes the active query. If you set a SQL string on a layer that already has that same query, it sets that as the active definition query, if it is not already active. The second way to manage definition queries is to use the listDefinitionQueries and updateDefinitionQueries functions in combination. The listDefinitionQueries function returns a list of Python dictionaries that represent the properties associated with each query. The dictionary keys are name, sql, and isActive. Definition queries can be added, modified, or removed from the Python list using core Python. The dictionary isActive value can be set to True to set the active query. Again, only one query can be active. If you try setting more than one query to be active, an error will be returned. After changes are made, the updateDefinitionQueries function is used to set the new changes.

Changing a layer's data source is a common requirement. For a more detailed discussion, parameter information, scenarios, and code samples, refer to the Updating and fixing data sources help topic.

プロパティ

プロパティ説明データ タイプ
brightness
(読み書き)

A layer's brightness value. The default, normal brightness, is 0 percent. Enter any value between +100 percent and -100 percent. Type a plus or minus sign to the left of the value to specify whether it is above or below 0.

Integer
connectionProperties
(読み取り専用)

Returns a layer's data source connection information as a Python dictionary.

Dictionary
contrast
(読み書き)

A layer's contrast value. The default, neutral contrast, is 0 percent. Enter any value between +100 percent and -100 percent. Type a plus or minus sign to the left of the value to specify whether it is above or below 0.

Integer
dataSource
(読み取り専用)

Returns the complete path for the layer's data source. It includes the full workspace path and name of the dataset. For enterprise geodatabase layers, a string containing the layer's connection information is returned.

ヒント:

Enterprise geodatabase layers in an ArcGIS Pro project do not retain the path to the database connection file (.sde) that was used to create the layer.

String
definitionQuery
(読み書き)

A layer's definition query. If you set a unique SQL string on a layer that does not have a definition query or a layer that has multiple definition queries, the new definition query is added and it becomes the active query. If you set a SQL string on a layer that already has that same query, it simply sets that as the active definition query, if it is not already active.

String
groupType
(読み取り専用)

Returns the type of group layer. The layer must be a group layer so it is best to first check if isGroupLayer is True. To set the groupType, use the setGroupType method. The possible values are:

  • CHECKBOXA checkbox style group layer.
  • RADIOA radio style group layer.
String
is3DLayer
(読み取り専用)

Returns True if a layer is a 3D layer.

Boolean
isBasemapLayer
(読み取り専用)

Returns True if a layer is a basemap layer.

Boolean
isBroken
(読み取り専用)

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

Boolean
isFeatureLayer
(読み取り専用)

Returns True if a layer is a feature layer.

Boolean
isGraphicsLayer
(読み取り専用)

Returns True if a layer is a graphics layer.

Boolean
isGroupLayer
(読み取り専用)

Returns True if a layer is a group layer.

Boolean
isNetworkAnalystLayer
(読み取り専用)

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

Boolean
isNetworkDatasetLayer
(読み取り専用)

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

Boolean
isParcelFabricLayer
(読み取り専用)

Returns True if a layer is a parcel fabric layer.

Boolean
isRasterLayer
(読み取り専用)

Returns True if a layer is a raster layer.

Boolean
isSceneLayer
(読み取り専用)

Returns True if a layer is a scene layer.

Boolean
isTimeEnabled
(読み取り専用)

Indicates whether time is enabled on the layer. If isTimeEnabled returns True, the time property on the layer can be used to return a LayerTime object. Use the enableTime method to enable time on a layer that contains time information.

Boolean
isWebLayer
(読み取り専用)

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. Esri basemaps are an example.

Boolean
longName
(読み取り専用)

A layer's full name including group layer and composite layer structure.

String
maxThreshold
(読み書き)

A layer's maximum scale threshold for 2D maps and its maximum distance above ground for 3D maps. A layer will not display when zoomed in beyond the maximum scale. To clear the maximum scale, set the value to 0.

Double
metadata
(読み書き)

Get or set the layer's Metadata class information.

注意:

Setting metadata is dependent on the isReadOnly property value.

Metadata
minThreshold
(読み書き)

A layer's minimum scale threshold for 2D maps and its maximum distance above ground for 3D maps. A layer will not display when zoomed out beyond the minimum scale. To clear the minimum scale, set the value to 0.

Double
name
(読み書き)

The name of a layer the way it would appear in the table of contents. Spaces can be included. It is important that all layers in a map have a unique name so they can be easily referenced by their names.

String
pageQuery
(読み取り専用)

Returns a Python-named tuple of page query properties.

  • fieldName The field name used in the page query.
  • match A boolean that indicates if the features are filtered when they match the current page of the map series.

注意:
Page query filters are only applied if the layer is in the MapFrame that is referenced in the MapSeries.

tuple
showLabels
(読み書き)

Controls the display of labels for a layer. If set to True, labels will display; if set to False, labels will not be drawn.

Boolean
symbology
(読み書き)

Provides access to a layer's symbology.

Object
time
(読み取り専用)

Returns a LayerTime object if time is enabled on the layer.

LayerTime
transparency
(読み書き)

A layer's transparency value. This enables you to see through a layer. Use values between 0 and 100. A value of 0 is not transparent. A transparency value of more than 90 percent usually results in the layer not being drawn at all.

Integer
URI
(読み取り専用)

The Universal Resource Indicator for a layer. It is a unique identifier for a layer in a project and is sometimes required when using Python CIM access. Once a layer is added and the URI is established, the value does not change over time. For example, if you modify the layer's name, the URI will not change.

String
visible
(読み書き)

Controls the display of a layer. If set to True, the layer will draw; if set to False, the layer will not be drawn.

Boolean

方法の概要

方法説明
createLabelClass (name, expression, {sql_query}, {labelclass_language})

The createLabelClass method creates a LabelClass for a layer.

disableTime ()

Disables time enabled properties on a Layer object.

enableTime ({startTimeField}, {endTimeField}, {autoCalculateTimeRange}, {timeDimension})

Enables time on a layer if it has time information.

extrusion ({extrusion_type}, {expression})

Extrudes 2D features in a layer to display 3D symbology.

getDefinition (cim_version)

Gets a layer's CIM definition.

getSelectionSet ()

Returns a layer's selection as a Python set of object IDs.

listDefinitionQueries ({wildcard})

Returns a Python list of definition queries associated with a layer.

listLabelClasses ({wildcard})

Returns a Python list of LabelClass objects in a layer.

listLayers ({wildcard})

Returns a Python list of Layer objects from a group layer or composite layer.

listTables ({wildcard})

Returns a Python list of Table objects that exist within a group layer.

pasteProperties (source_layer, {layer_paste_properties})

The pasteProperties method pastes properties from a feature layer to another feature layer.

saveACopy (file_name)

Saves a layer to a layer file (.lyrx).

setDefinition (definition_object)

Sets a layer's CIM definition.

setGroupType (group_type)

The setGroupType method sets a layer's group type.

setPageQuery ({field_name}, {match})

The setPageQuery method sets a page query filter for the layer.

setSelectionSet ({oidList}, {method})

Sets a layer's selection using a Python list of Object IDs.

supports (layer_property)

Used to determine if a particular layer type supports a property on the layer object. Not all layers support the same set of properties; the supports property can be used to test if a layer supports that property before attempting to set it.

updateConnectionProperties (current_connection_info, new_connection_info, {auto_update_joins_and_relates}, {validate}, {ignore_case})

The updateConnectionProperties method replaces connection properties using a dictionary or a path to a workspace.

updateDefinitionQueries (definitionQueries)

Updates a layer's collection of definition queries.

updateLayerFromJSON (json_data)

Updates a Layer from a JSON string.

方法

createLabelClass (name, expression, {sql_query}, {labelclass_language})
パラメーター説明データ タイプ
name

The name of the new label class. Names must be unique.

String
expression

An expression to be applied. Its syntax must match the labelclass_language value.

(デフォルト値は次のとおりです None)

String
sql_query

An optional query that is useful for restricting the features that are labeled.

String
labelclass_language

The following are the supported scripting languages.

  • ARCADEArcade
  • JSCRIPTJScript
  • PYTHONPython
  • VBSCRIPTVBScript

(デフォルト値は次のとおりです ARCADE)

String
戻り値
データ タイプ説明
LabelClass

If a variable is provided, it will reference the newly returned LabelClass object.

Newly added label classes may not display initially. There are two levels of settings to display labels. First, the Layer class has a property called showLabels and needs to be set to True. Second, each LabelClass has a visible property and it also needs to be set to True. Refer to the LabelClass help topic for more information and code samples.

disableTime ()

The enableTime method can be used to re-enable time properties.

enableTime ({startTimeField}, {endTimeField}, {autoCalculateTimeRange}, {timeDimension})
パラメーター説明データ タイプ
startTimeField

The name of the field containing the start time values. If each feature has a single time field, specify that field name in the startTimeField and leave endTimeField blank. If each feature has a start and end time field, specify both the startTimeField and endTimeField.

(デフォルト値は次のとおりです None)

String
endTimeField

The name of the field containing the end time values. Not all layers use an end time field. If each feature has a single time field, specify that field name in the startTimeField and leave endTimeField blank. If each feature has a start and end time field, specify both the startTimeField and endTimeField.

(デフォルト値は次のとおりです None)

String
autoCalculateTimeRange

If set to True, the start and end time attribute information is used to calculate the layer's time extent.

(デフォルト値は次のとおりです True)

Boolean
timeDimension

The name of the dimension containing time values when using netCDF data.

(デフォルト値は次のとおりです None)

String

All parameters on the enableTime method are optional. If startTimeField and endTimeField are not specified, the method will evaluate the data and attempt to come up with appropriate default values.

After running the enableTime method, the time property on the layer can be used to return a LayerTime object. If a MapFrame on a Layout contains time-enabled layers, the MapTime class can be used to access map time settings.

extrusion ({extrusion_type}, {expression})
パラメーター説明データ タイプ
extrusion_type

A string that specifies the extrusion method. The default value is NONE which turns off layer extrusion.

  • ABSOLUTE_HEIGHTThe feature is extruded to the specified z-value, as a flat top, regardless of the z-values of the feature.
  • BASE_HEIGHTA z-value is calculated for each vertex of the feature's base, and the feature is extruded to the various z-values creating a multifaceted top.
  • MAX_HEIGHTAdds extrusion height to the minimum z-value of the feature, and the feature is extruded to a flat top at that value.
  • MIN_HEIGHTAdds extrusion height to the minimum z-value of the feature, and the feature is extruded to a flat top at that value.
  • NONEFeatures are not extruded.

(デフォルト値は次のとおりです NONE)

String
expression

A string that defines the extrusion expression, which provides an absolute extrusion height for each feature.

(デフォルト値は次のとおりです None)

String

Extrusion is the process of vertically stretching a flat 2D shape to create a 3D object. This provides a method to create three-dimensional symbology from two-dimensional features. Polygon and line features have all five extrusion_type options available; point features don't use MAX_HEIGHT or MIN_HEIGHT options.

getDefinition (cim_version)
パラメーター説明データ タイプ
cim_version

A string that represents the major version of the CIM.

String
戻り値
データ タイプ説明
Object

Returns the CIM definition for a Layer object.

CIM-level access to additional object properties was introduced at ArcGIS Pro 2.4. When you want to return an object's CIM definition, you must specify a cim_version. Esri follows the semantic versioning specification. This means that at major releases—for example, 3.0—breaking API changes are allowed. This allows Python script authors control over which version of the CIM is used during a script run if there is a possibility breaking changes may be introduced in the new version. If you are authoring scripts for ArcGIS Pro 2.x, specify the cim_version to be 'V2'. If you are authoring scripts for ArcGIS Pro 3.x, specify the cim_version to be 'V3'. Scripts authored using cim_version 'V2' will continue to work in ArcGIS Pro 3.x.

For more information about working with the CIM and samples, see Python CIM access.

getSelectionSet ()
戻り値
データ タイプ説明
List

Returns the CIM definition for a BookmarkMapSeries.

Returns a layer's selection as a Python set of Object IDs.

listDefinitionQueries ({wildcard})
パラメーター説明データ タイプ
wildcard

A wildcard is based on the query name and is not case sensitive. A combination of asterisks (*) and characters can be used to limit the resulting list.

(デフォルト値は次のとおりです None)

String
戻り値
データ タイプ説明
List

A Python list of dictionaries that represent the properties associated with each query. The dictionary keys are name, sql, and isActive.

Definition queries can be added, modified, or removed from the Python list using standard practices. The dictionary isActive value can be set to True to set the active query. Again, only one query can be active. If you try setting more than one query to be active, an error will be returned. After changes are made, the updateDefinitionQueries function is used to set the new changes.

listLabelClasses ({wildcard})
パラメーター説明データ タイプ
wildcard

A wildcard is based on the label class name and is not case sensitive. A combination of asterisks (*) and characters can be used to help limit the resulting list.

(デフォルト値は次のとおりです None)

String
戻り値
データ タイプ説明
List

Returns a Python list of LabelClass objects in a layer.

Returns a Python list of LabelClass objects in a layer.

listLayers ({wildcard})
パラメーター説明データ タイプ
wildcard

A wildcard is based on the layer name and is not case sensitive. A combination of asterisks (*) and characters can be used to help limit the resulting list.

(デフォルト値は次のとおりです None)

String
戻り値
データ タイプ説明
List

Returns a Python list of Layer objects from a group layer or composite layer.

Returns a Python list of Layer objects from a group layer or composite layer.

listTables ({wildcard})
パラメーター説明データ タイプ
wildcard

A wildcard is based on the table name and is not case sensitive. A combination of asterisks (*) and characters can be used to limit the resulting list.

(デフォルト値は次のとおりです None)

String
戻り値
データ タイプ説明
List

A Python list of Table objects in a layer.

Returns a Python list of Table objects that exist within a group layer. ListTables always returns a list object even if only one table is returned.

It is possible that there may be tables in a group layer with the same name. If this is the case, other properties may need to be used to isolate a specific layer. Properties such as a tables's datasource or definitionQuery or URI can be used to do this. It is ideal that all tables be uniquely named.

pasteProperties (source_layer, {layer_paste_properties})
パラメーター説明データ タイプ
source_layer

A feature layer with the properties that will be pasted.

Layer
layer_paste_properties
[layer_paste_properties,...]

A single string or a list of strings that specify the property or properties that will be pasted. For example, layer_paste_properties="SYMBOLGY" will paste only symbology properties, whereas layer_paste_properties=["SYMBOLGY", "LABELING", "VISIBILITY_RANGE"]) will paste multiple properties.

  • ALLAll applicable properties will be pasted.
  • CHARTSOnly chart properties will be pasted.
  • DEFINITION_QUERIESOnly definition query properties will be pasted.
  • DISPLAY_EXPRESSIONOnly display expression properties will be pasted.
  • DISPLAY_FILTERSOnly display filter properties will be pasted.
  • FIELD_PROPERTIESOnly field properties will be pasted.
  • LABELINGOnly labeling properties will be pasted.
  • POPUPSOnly pop-up configuration properties will be pasted.
  • SYMBOLOGYOnly symbology properties will be pasted.
  • VISIBILITY_RANGEOnly visibility range properties will be pasted.

(デフォルト値は次のとおりです ALL)

String

For more information about pasting feature layer properties, see the Copy and paste properties help topic.

saveACopy (file_name)
パラメーター説明データ タイプ
file_name

A string that includes the location and name of the output layer file (.lyrx).

String

If a group layer is being saved, all of the layers below it in the TOC will also be saved to the layer file (.lyrx).

setDefinition (definition_object)
パラメーター説明データ タイプ
definition_object

A modified CIM definition object originally retrieved using getDefinition.

Object

For more information about working with the CIM and samples, see Python CIM access.

setGroupType (group_type)
パラメーター説明データ タイプ
group_type

A string that specifies the selection method that will be used.

  • CHECKBOXThe group layer will be set to a check box style.
  • RADIOThe group layer will be set to a radio style.
String

When creating group layers, the default group layer type is CHECKBOX. This style allows multiple layers in the same group to be visible at the same time. The RADIO style allows only one layer in the group to be visible at a time. The RADIO style is required when creating a thematic map series.

setPageQuery ({field_name}, {match})
パラメーター説明データ タイプ
field_name

The name of the field that contains values that match the map series page name field in the index layer.

(デフォルト値は次のとおりです None)

String
match

If set to True, features with the same map series page name will be displayed, if False, the inverse set of features will be displayed.

(デフォルト値は次のとおりです True)

Boolean

Page query filters are only applied if a MapSeries is enabled on a Layout and the layer is used in the MapFrame that the map series is set to. If a field_name is not provided, the page query gets reset to None.

setSelectionSet ({oidList}, {method})
パラメーター説明データ タイプ
oidList
[oidList,...]

A Python list of Object IDs to use along with the appropriate selection method.

(デフォルト値は次のとおりです None)

Integer
method

A string that specifies which selection method to use.

  • NEWCreates a new feature selection from the oidList.
  • DIFFERENCESelects the features that are not in the current selection but are in the oidList.
  • INTERSECTSelects the features that are in the current selection and the oidList.
  • SYMDIFFERENCESelects the features that are in the current selection or the oidList but not both.
  • UNIONSelects all the features in both the current selection and those in the oidList.

(デフォルト値は次のとおりです NEW)

String

This method provides an easy way to manage a layer's selection. To clear the selection, use the NEW selection method with an empty list or don't set any parameters.

Note: Python Lists are used for setting the oidList but Python Sets get returned from the getSelectionSet method on the Layer object.

supports (layer_property)
パラメーター説明データ タイプ
layer_property

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

  • BRIGHTNESSA raster layer's brightness value.
  • CONNECTIONPROPERTIESA Layer's connection information.
  • CONTRASTA raster layer's contrast value
  • DATASOURCEA layer's file path or connection file.
  • DEFINITIONQUERYA layer's definition query string.
  • LONGNAMEA layer's path including the group layers it may be nested within.
  • MAXTHRESHOLDA layer's maximum threshold to display the features.
  • METADATAA layer that can persist metadata.
  • MINTHRESHOLDA layer's minimum threshold to display the features.
  • NAMEA layer's name.
  • SHOWLABELSA layer that can display labels.
  • SYMBOLOGYA layer that symbology can be accessed.
  • TIMEA layer's time properties.
  • TRANSPARENCYA layer's transparency value.
  • URIA layer's Universal Resource Identifier.
  • VISIBLEA layer's visibility state.

(デフォルト値は次のとおりです name)

String
戻り値
データ タイプ説明
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 supports 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.

Boolean properties don't need to be tested using supports because if a layer property isn't supported for that layer type, a False value gets returned.

updateConnectionProperties (current_connection_info, new_connection_info, {auto_update_joins_and_relates}, {validate}, {ignore_case})
パラメーター説明データ タイプ
current_connection_info

A string that represents the workspace path or a Python dictionary that contains connection properties to the source you want to update. If an empty string or None is used in current_connection_info, all connection properties will be replaced with the new_workspace_info, depending on the value of the validate parameter.

String
new_connection_info

A string that represents the workspace path or a Python dictionary that contains connection properties with the new source information.

String
auto_update_joins_and_relates

If set to True, the updateConnectionProperties method will also update the connections for associated joins or relates.

(デフォルト値は次のとおりです True)

Boolean
validate

If set to True, the connection properties will only be updated if the new_connection_info value is a valid connection. If it is not valid, the connection will not be replaced. If set to False, the method will set all connections to match the new_connection_info value, regardless of a valid match. In this case, if a match does not exist, the data sources would be broken.

(デフォルト値は次のとおりです True)

Boolean
ignore_case

Determines whether searches will be case sensitive. By default, queries are case sensitive. To perform queries that are not case sensitive, set ignore_case to True.

(デフォルト値は次のとおりです False)

Boolean

For more detailed discussion, parameter information, scenarios, and code samples, see Updating and fixing data sources.

updateDefinitionQueries (definitionQueries)
パラメーター説明データ タイプ
definitionQueries
[definitionQueries,...]

Updates a list of dictionaries that represent the properties of each definition query.

List

This function is typically used to apply the changes that have been made to the results returned by the listDefinitionQueries function.

updateLayerFromJSON (json_data)
パラメーター説明データ タイプ
json_data

The layer definition in JavaScript Object Notation (JSON) format. See the ExportWebMap JSON specification for more information. ArcGIS API for JavaScript and ArcGIS Web AppBuilder allow you to get this JSON string from the web app. The layer definition is a subset of the webmap_json used in the ConvertWebMapToArcGISProject function. You don't need to create the web map JSON; the APIs take care of it for you. However, you need to extract the layer definition from the full webmap_json.

String

This function is intended to be used in a web tool that uses the ConvertWebMapToArcGISProject function in web map printing applications that support changing the renderer (or other properties) of dynamic web service layers. If your web tool replaces the service layers with staged vector layers after running ConvertWebMapToArcGISProject, updateLayerFromJSON will apply the renderer (or other layer properties) as specified in the webmap_json to the corresponding vector layers staged in the layout template. For more information and a code sample, see ConvertWebMapToArcGISProject.

コードのサンプル

Layer example 1

The following script prints the name of each map in a project and lists the names of the layers in each map. The script also appends a (BROKEN) prefix to the layer name if it has a broken data source.

import arcpy
aprx = arcpy.mp.ArcGISProject(r"C:\Projects\YosemiteNP\Yosemite.aprx")
for m in aprx.listMaps():
    print("Map: {0} Layers".format(m.name))
    for lyr in m.listLayers():
        if lyr.isBroken:
            print("(BROKEN) " + lyr.name)
        else:
            print("  " + lyr.name)
del aprx
Layer example 2

The following script clears all layer definition queries and turns off labels for all layers in a map named Yosemite National Park:

import arcpy
aprx = arcpy.mp.ArcGISProject(r"C:\Projects\YosemiteNP\Yosemite.aprx")
m = aprx.listMaps("Yosemite National Park")[0]
for lyr in m.listLayers():
    if lyr.supports("DEFINITIONQUERY"):
        lyr.definitionQuery = ""
    if lyr.supports("SHOWLABELS"):
        lyr.showLabels = False
aprx.save()
del aprx
Layer example 3

The following script adds a new definition query to a layer or sets the same query to be the active definition query if the SQL string already exists:

p = arcpy.mp.ArcGISProject('current')
m = p.listMaps()[0]
l = m.listLayers()[0]
if l.supports('DefinitionQuery'):
  l.definitionQuery = "AREA > 3000000"
Layer example 4

The following script creates a new definition query by appending a Python dictionary to the existing list queries. Because a query may already be active, it is important to first clear existing active queries before setting the new active query.

p = arcpy.mp.ArcGISProject('current')
m = p.listMaps()[0]
l = m.listLayers()[0]
if l.supports('DefinitionQuery'):
  #Get the list of definition queries
  dql = l.listDefinitionQueries()
  #Clear active definition queries otherwise the update will fail if there is already an active query
  for dq in dql:
    dq['isActive'] = False
  #Create a new definition query and append it to the list
  dql.append({'name': 'Appended Query', 'sql': "name = 'Lake Superior'", 'isActive': True})
  #Update the definition queries with the newly modified list
  l.updateDefinitionQueries(dql)