Задать вопрос

Тел: +7 965 3737 888

453

Просмотров

0

Ответов

SuperChoices

<p>Seeing <a href="http://foothold.ru/knowledge/detail/choices-class.html">snippet 1178</a> reminded me that I also had a go at writing a Choices class at some point. I'm content with the result, but I doubt xgettext will discover your translation strings, which will no doubt be inconvenient.</p>
<p>Here it is anyway, in all its overly-complicated glory :-)
The following demo was pulled from the function's docstring tests.</p>
&gt;&gt;&gt; simple = Choices("one", "two", "three")
&gt;&gt;&gt; simple
Choices(one=0, two=1, three=2)
&gt;&gt;&gt; tuple(simple)
((0, u'ein'), (1, u'zwei'), (2, u'drei'))

&gt;&gt;&gt; (0, _('one')) in simple
True
&gt;&gt;&gt; simple.ONE
0
&gt;&gt;&gt; hasattr(simple, 'FOUR')
False

<p>Ordering just follows the order that positional arguments were given. Keyword arguments are ordered by their value at appear after positional arguments.</p>
&gt;&gt;&gt; [ key for key, val in simple ]
[0, 1, 2]

&gt;&gt;&gt; Choices(one=1, two=2, three=3)
Choices(one=1, two=2, three=3)

<p>A Mix of keyword and non-keyword arguments</p>
&gt;&gt;&gt; Choices("one", two=2, three=3)
Choices(one=0, two=2, three=3)

<p>Automatically generated values (for "one" below) should not clash.</p>
&gt;&gt;&gt; Choices("one", none=0, three=1, four=2)
Choices(one=3, none=0, three=1, four=2)

<p>Here is an example of combined usage, using different object types.</p>
&gt;&gt;&gt; combined = Choices(one=1, two="two", three=None, four=False)
&gt;&gt;&gt; len(combined)
4
&gt;&gt;&gt; (1, _('one')) in combined
True
&gt;&gt;&gt; ('two', _('two')) in combined
True
&gt;&gt;&gt; (None, _('three')) in combined
True
&gt;&gt;&gt; (False, _('four')) in combined
True

<p>And here is an empty choices set. Not sure why you would want this....</p>
&gt;&gt;&gt; empty = Choices()
&gt;&gt;&gt; empty
Choices()

Вопрос полезен? Да0/Нет0
file_2322.py(2.2Кб)
None