this a question about code efficiency, not asking how to loop through layers. I'm getting the 'this question appears subjective...' warning but there must be a tried and tested method by someone more adept at PyQGIS programming than me! I don't intend to start a discussion, just hopefully someone more experienced can objectively say "do it like this instead" or "that's the best/only way".
I'm only just starting to use QGIS and PyQGIS to develop...stuff. Most of the operations I will be doing, and indeed all of them up until this point, will be using some layer that's in the map registry. So every function I have so far starts like this:
def some_function(layer, parameter, another_parameter):
for lyr in iface.mapCanvas().layers():
if lyr.name() == layer:
# and then whatever it is I need to do or get from this layer
Is this the most efficient way of going about this, or is there another way of proceeding without looping through all layers and then having the if
statement to ID the layer. Clearly the more layers you have open, the more computationally expensive this would be, perhaps there is a way of selecting the layer by its name directly?