Python Basics for AppDaemon: A Beginner's Guide for Home Assistant Users
New to Python? Don't worry - writing AppDaemon apps for Home Assistant is a great way to learn practical Python, even if you've never coded before! This guide will introduce Python's key concepts, explain the basic syntax, and break down each part of a typical AppDaemon script. No prior programming experience required.
1. Python Fundamentals: The Very Basics
- Whitespace matters: Python uses indentation (spaces) to show which lines belong together. Don't mix tabs and spaces!
- Comments start with # and are ignored by Python.
# This is a comment. Python skips it. - Variables store information:
name = "Home Assistant" count = 3 - Strings are text in quotes:
message = "Hello, world!" - Numbers are written directly:
brightness = 128 temperature = 21.5 - Lists are like arrays - collections of items:
devices = ["light.kitchen", "light.bedroom"] - Dictionaries (like YAML mappings) hold pairs:
sensor = {"state": 21.5, "unit": "°C"} - Functions define reusable chunks of code:
def say_hello(): print("Hello!")
2. AppDaemon Script Structure: Breaking it Down
All AppDaemon apps follow a basic pattern. Here's what each part means:
import appdaemon.plugins.hass.hassapi as hass
class MyApp(hass.Hass):
def initialize(self):
self.log("App started!")
# Setup code goes here
def my_action(self, entity, attribute, old, new, kwargs):
self.log(f"{entity} changed from {old} to {new}")
- import appdaemon.plugins.hass.hassapi as hass
- This line loads the special Home Assistant helper code for AppDaemon apps.
- class MyApp(hass.Hass):
- All AppDaemon apps are written as classes (think: templates or blueprints for your automation).
- By inheriting from
hass.Hass, your app can use all AppDaemon functions.
- def initialize(self):
- This special function runs when your app starts. Put your setup or listeners here.
- self.log("...")
- Writes a message to the AppDaemon log - great for debugging.
- def my_action(self, ...):
- This is a function (method) your app calls in response to something (like an entity changing).
- You can name your functions anything you like.
3. Common AppDaemon Functions (with Python Basics)
- Listening for state changes:
self.listen_state(self.my_action, "light.kitchen")- "When light.kitchen changes, run my_action."
- Calling a service:
self.call_service("light/turn_on", entity_id="light.kitchen") - Getting a state:
state = self.get_state("sensor.living_room_temp") - If/else (decision making):
if state == "on": self.turn_off("light.kitchen") else: self.turn_on("light.kitchen") - Formatting text (f-strings):
entity = "light.kitchen" state = "on" message = f"{entity} is now {state}"- The
fbefore the quotes means Python will insert variables right into the text.
- The
4. Putting It All Together: A Simple Example
import appdaemon.plugins.hass.hassapi as hass
class HelloLight(hass.Hass):
def initialize(self):
self.listen_state(self.on_light, "light.kitchen")
def on_light(self, entity, attribute, old, new, kwargs):
if new == "on":
self.call_service("notify/persistent_notification",
message="The kitchen light was turned on!")
- What's happening?
- When the kitchen light turns on, Home Assistant will show a notification.
5. Common Python Pitfalls for Beginners
- Indentation errors: Always use 4 spaces per indentation level. Never mix tabs and spaces.
-
After if,else,def, andclasslines, always use a colon. -
Case sensitivity:
Light.Kitchenis not the same aslight.kitchenin Python! -
Quotes: Strings can use single (
') or double (") quotes, but they must match.
6. Learning More
- Try changing the messages, entity names, or actions in the examples above.
- Use the Learn Python interactive tutorials to practice.
- Check the AppDaemon documentation for more examples and a list of all the helper functions you can use.
- Don't be afraid to experiment - if your script doesn't work, check the AppDaemon logs for helpful error messages.