Using Include to Simplify Code

I have a bunch of ESP32 based environmental sensors around my house that use the same code because they all use the same sensors, but also have some unique code because of unique sensors.

I’ve been trying to experiment with using !include to make the code leaner (only need to edit one copy when making changes), but I can’t seem to find the correct formatting.

Let’s assume I have two sensors. A “abc123” sensor which is unique to that device, and a “xyz321” sensor which is common across all my devices. So I want to put xyz321’s code in a separate yaml.

Which of the following is correct?

#example 1
sensor:
  - platform: abc123
    ...
	
<<: !include sensor_xyz321.yaml

with no dash or indent before the include
or

#example 2
sensor:
  - platform: abc123
    ...

  - <<: !include sensor_xyz321.yaml

with dash and indent before the include
or

#example 3
sensor:
  - platform: abc123
    ...
	
  <<: !include sensor_xyz321.yaml

with indent but no dash


And then should the contents of sensor_xyz321.yaml be

#example 4
platform: xyz123
...

with no dash or indents
or

#example 5
  - platform: xyz123
    ...

with dash and indents
or

#example 6
sensor:
  - platform: xyz123
    ...

with a re-declaration of sensor along with dash and indents

note: I numbered the examples to make them easier to refer to


And if multiple possibilities work, is there an advantage to one vs the other?

I personally prefer the use of packages and substitutions Configuration Types — ESPHome

That guide was actually where my idea partly came from. And actually, my follow-on question once I got an answer to the one above, was going to be "Why does the guide suggest doing the include as

packages:
  wifi: !include common/wifi.yaml

versus just

<< !include common/wifi.yaml

Does the resulting merged code end up different with one vs the other?


But back to my original question, you can see that even in the example they give, the sensor section in device_base.yaml has includes within it. Unfortunately, the person who wrote this stopped short and didn’t bother to show the content of uptime.config.yaml, etc.

The example in the guide is formatted like my example #2 (i.e. including the indent and dash), but I’ve tried using that and I still get errors when I compile. That could be because I don’t have the content of uptime.config.yaml (or sensor_xyz321.yaml in my examples) correct or it could be because I’m mixing declaring platforms in the main config and in includes.

If anyone has a config where they use an include inside of a component (as opposed to an include of an entire component) and would be willing to post both the include statement and the yaml in the included file, I’d really appreciate it.