0

我知道settingslogic-gem来自红宝石。这允许一种非常优雅的方式来为您的应用程序定义默认设置或回退设置,如settingslogic example中所述。

我正在阅读,PyYaml但还没有找到这么好的方法来做到这一点。

你将如何以优雅和 Pythonic 的方式解决这样的问题?

4

1 回答 1

1

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
于 2013-08-19T23:00:22.003 回答