Frage

I know the settingslogic-gem from ruby. This allows a very elegant way to define default settings or fallback-settings for your application as described in settingslogic example.

I'm reading through PyYaml but didn't find yet such a nice way to do this.

How would you solve such a problem in an elegant and pythonic way?

War es hilfreich?

Lösung

I'm not sure why you expect a YAML-parsing library to provide multi-layered settings fallback. Ruby's YAML-parsing library certainly doesn't, which is why there are separate wrapper gems like the one you referred to in the first place.

But if you look at what you linked to, there isn't really any logic in the library at all; the application logic code has to use ||= to set the value if it's missing. You can do the same thing in Python; it's just spelled different.

In Ruby, you use dot-access if you want an exception on missing key, brackets if you want nil, brackets plus || if you want a different default value, and a slightly hacky but idiomatic brackets plus ||= if you want to set and return a different default value.

In Python, you use brackets if you want an exception on missing key, get if you want None, get with an argument is you want a different default, and setdefault if you want to set and return a different default. So, this Ruby code:

>> settings.messaging['queue_name'] ||= 'user_mail'
=> "user_mail"

… looks like this in Python:

>>> settings['messaging'].setdefault('queue_name', 'user_mail')
user_mail
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top