0

Suppose it is the following structure given:

from django.utils.translation import ugettext_lazy as _

# Constants for all available difficulty types.
SIMPLE = 1
MEDIUM = 2
DIFFICULT = 3

# Names for all available difficulty types.
DIFFICULTIES = (
    (SIMPLE, _("simple")),
    (MEDIUM, _("medium")),
    (DIFFICULT, _("difficult")),
)

How do you get the string value, if a constant is given?

A loop is easy to program, but is there a shorter python-like way with a single expression?

The expression

DIFFICULTIES[SIMPLE][1]

returns the string "medium". What is obviously wrong.

4
  • 3
    Are you searching for dictionary? Commented Nov 11, 2012 at 14:39
  • What are the underscores doing in there? _("simple") doesn't look like syntactically valid Python to me. Commented Nov 11, 2012 at 14:43
  • I'd guess that the underscores were there as references to gettext's _ function for internationalization (see here). Commented Nov 11, 2012 at 14:53
  • @DSM: I see, interesting. It seems a bit unpythonic though. Commented Nov 11, 2012 at 14:55

3 Answers 3

2

Of course you can use a dict, but the array is given.

So exchange it. (I'm assuming you kept the receipt..)

>>> dict(DIFFICULTIES)
{1: 'simple', 2: 'medium', 3: 'difficult'}
>>> d = dict(DIFFICULTIES)
>>> d[MEDIUM]
'medium'

Searching through an unsorted tuple for something simply isn't the right way to go about things. I suppose you could do

>>> next(v for k,v in DIFFICULTIES if k == MEDIUM)
'medium'

if you wanted to avoid a for loop with a colon, but that's a little silly.

Sign up to request clarification or add additional context in comments.

1 Comment

Great, thanks! I've searched this expression dict(DIFFICULTIES)[SIMPLE]
1

it just because you specified a tuple, an indexing starting from 0, you either need to switch to dictionary or modify your constants with correct values:

DIFFICULTIES = {SIMPLE: "simple", MEDIUM: "medium", DIFFICULT: "difficult"}

OR:

SIMPLE, MEDIUM, DIFFICULT = range(3)

2 Comments

Then what about second suggestion about const chg
Would be a possibility, but I do not know how it impacts on the whole project, because other dependencies exist. I will solve it with a loop. Thought there would be a shorter solution.
0

Use a dictionary:

SIMPLE, MEDIUM, DIFFICULT = range(3)
DIFFICULTIES = {
    SIMPLE: _("simple"),
    MEDIUM: _("medium"),
    DIFFICULT: _("difficult")
}
DIFFICULTIES[SIMPLE] # will return "simple"

3 Comments

NameError: name '_' is not defined
I just copied the code from the question. Guess those _ and the brackets gotta go
Then the only thing you can do is to go with Artsiom Rudzenka's answer (let the index start at 0, not at 1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.