How do I create a new label class using arcpy?

929
5
07-30-2020 06:01 PM
Per_Åke_MattiasWallin
New Contributor III

I am using ArcPro 2.6 and I can modify existing label classes no problem. But what I want to do is to create a new label class using arcpy- I just cannot figure it out, what am I missing? All example’s I come across starts with listLabelClasses which assumes the class already exists.

Thanks.

5 Replies
DanPatterson
MVP Esteemed Contributor

From here

Layer—ArcGIS Pro | Documentation 

listLabelClasses ({wildcard})

Returns a Python list of LabelClass objects in a layer.

Which means you have to have something to create the labels from, and as you know...

LabelClass—ArcGIS Pro | Documentation
with the warning

Not all layers support labeling, so it is useful to test this ahead of time using the supports method on the Layer object. For example:

if lyr.supports("SHOWLABELS"):

where you can modify them.

But I don't know what you would use as a base except for an existing file


... sort of retired...
0 Kudos
Per_Åke_MattiasWallin
New Contributor III

Thank you for your reply Dan.

I was able to create a new label class using this:

# Create a new label class
new_label_class = arcpy.cim.CreateCIMObjectFromClassName('CIMLabelClass','V2')
new_label_class.name = 'Class 2'
cim_industry.labelClasses.append(new_label_class)

However...  whenever I try to use the layer that I created the new label class on it crashes ArcPro so something gets corrupted...  which they do wanrn about here, Python CIM access—ArcGIS Pro | Documentation 

Per_Åke_MattiasWallin
New Contributor III

I just noticed that there is a feature request https://community.esri.com/ideas/6533  from 2012 with 9 votes...

0 Kudos
by Anonymous User
Not applicable

I am also noticing the same thing. I use arcpy.cim.CreateCIMObjectFromClassName('CIMLabelClass','V2') and then append it into the list of label classes. When I go to interact with the new label class in the GUI ArcPro immediately crashes. 

0 Kudos
Nicholas_G
Esri Contributor

It may be easier to try the  arcpy.cim.CIMLabelClass() to create a new label class

 

Essentially I think you can get your layer object and export out a version of the cim object like this.

cimObject = LayerObj.getDefinition(‘v2’)

 

From here I would use arcpy.cim.CIMLabelClass() to create a new label placement object and set all of the properties to your liking.

Then append this new object to the cimObject label class list.

Something like  cimObject.labelClasses.append(new label class obj)

Check the cimObject.labelClasses to see if its in there.

Then go ahead and set its definition like this

LayerObj.setDefinition(cimObject)

 

This should work, I don’t think you will see it in the Pro interface under the labelling tab but the label class should be added to your layer object.