Does python charms require charmhelpers?

In the same way that any other language can implement a charm, it is possible for a python charm to be written without charmhelpers. What that would end up looking like is something along these lines:

#!/usr/bin/python3
import json
import subprocess

def main():
  # Let's call this a relation-changed hook where I need to get some config and set data on a relation
  config_raw = subprocess.check_output(['config-get', '--all', '--format=json'])
  config = JSON.parse(config_raw)
  value = config.get("value") # No idea what kind of config we want, but this should serve nicely ;-)
  key = 'my_awesome_relation_key'
  subprocess.check_call(['relation-set', '{}={}'.format(key, value)])

if __name__ == '__main__':
  main()

By the end of the above block, we’re read some config, parsed the JSON that it got returned as, and then set some data on a relation. It’s a bit brittle, as there are a lot of potential exceptions we’re not handling but hey, it works without charmhelpers!

On the other hand, we could write the same, with charmhelpers, as:

#!/usr/bin/python3
from charmhelpers.core.hookenv import ( config_get, relation_set )

def main():
  # Let's call this a relation-changed hook where I need to get some config and set data on a relation
  rel_data = {
    'my_awesome_relation_key': config().get("value") # 1, below
  }
  relation_set(rel_data) # 2, below

if __name__ == '__main__':
  main()

These helper functions are quite a bit more complex than my basic examples above, see:
1: https://github.com/juju/charm-helpers/blob/1989f1f255baefb34cba7863606915dcd4ef1e38/charmhelpers/core/hookenv.py#L425
2: https://github.com/juju/charm-helpers/blob/1989f1f255baefb34cba7863606915dcd4ef1e38/charmhelpers/core/hookenv.py#L479

3 Likes