code: def set_layer_visible(layer, visible):
          
          if layer is None:
              return
  
          QgsProject.instance().layerTreeRoot().findLayer(
              layer.id()).setItemVisibilityChecked(visible)
docs: Sets a layer in the project visible or not
  
          :param layer: layer to change
          :type layer: QgsMapLayer
  
          :param visible: True to show layer, False to hide layer
          :type visible: bool