Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a couple of options for how to proceed.</p> <p>The simplest might be to use nested dictionaries, so <code>Variable_FOO</code> becomes <code>config["variable"]["FOO"]</code>. You might want to use a <code>defaultdict(dict)</code> for the outer dictionary so you don't need to worry about initializing the inner ones when you add the first value to them.</p> <p>Another option would be to use tuple keys in a single dictionary. That is, <code>Variable_FOO</code> would become <code>config[("variable", "FOO")]</code>. This is easy to do with code, since you can simply assign to <code>config[tuple(some_string.split("_"))]</code>. Though, I suppose you could also just use the unsplit string as your key in this case.</p> <p>A final approach allows you to use the syntax you want (where <code>Variable_FOO</code> is accessed as <code>config.Variable["FOO"]</code>), by using <code>__getattr__</code> and a <code>defaultdict</code> behind the scenes:</p> <pre><code>from collections import defaultdict class Config(object): def __init__(self): self._attrdicts = defaultdict(dict) def __getattr__(self, name): return self._attrdicts[name] </code></pre> <p>You could extend this with behavior for <code>__setattr__</code> and <code>__delattr__</code> but it's probably not necessary. The only serious limitation to this approach (given the original version of the question), is that the attributes names (like <code>Variable</code>) must be legal Python identifiers. You can't use strings with leading numbers, Python keywords (like <code>global</code>) or strings containing whitespace characters.</p> <p>A downside to this approach is that it's a bit more difficult to use programatically (by, for instance, your config-file parser). To read a value of <code>Variable_FOO</code> and save it to <code>config.Variable["FOO"]</code> you'll probably need to use the global <code>getattr</code> function, like this:</p> <pre><code> name, value = line.split("=") prefix, suffix = name.split("_") getattr(config, prefix)[suffix] = value </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload