Why doesn't a dictionary work in classes?
uri at speedy.net
Wed Dec 26 00:10:32 EST 2018
Thank you all for your replies. After the first reply (about indentation) I
submitted a similar question on Stack Overflow, and I found out there that
a similar question has been asked before and I saw the answer there. The
indentation looks better on Stack Overflow than in email messages,
sorry about that.
By the way, I remember having a problem in the past when writing a list
comprehension which uses a variable name that was also used outside
the list comprehension. for example "[i * 2 for i in range(n)]" when i is
used outside. This had the side effect of changing the variable i and it
took me a long time to debug it since I didn't expect it. But I think then
it was Python 2.7 and I'm glad it's been fixed in Python 3. But, I didn't
expect a list comprehension not to be able to access variables in this
scope. I also think this is a bug in Python. And by the way, I used list
comprehensions above too. For example, [choice for choice in
GENDER_CHOICES] is also a list comprehension. It is not intuitive why
some list comprehensions work and others don't work.
If you want to see the full code with the branch I'm currently working on,
you can check
- for example this code is on
אבי (Avi), there are methods but I didn't include them in this email
because I thought they are not relevant to my question.
I used upper case for constants as I understand this is the convention.
Actually, I did consider to use all lowercase Python (including class names
and constants) but another programmer told me it's not the way Python is
I also tried to use "ALL_GENDERS = [__class__.GENDERS_DICT[gender] for
gender in __class__.GENDER_VALID_VALUES]" but this also didn't work there.
I don't like defining User.ALL_GENDERS after the end of the definition
of class User and as far as I remember this is the only time I defined a
class like that, but I didn't think I have any choice here. I don't want to
hack the definition as you suggested. I know since this list contains only
3 elements, I could define them specifically. But I didn't want to do it.
You can see in the tests that I defined it in 3 ways and tested they are
list2=[User.GENDERS_DICT[gender] for gender in User.GENDER_VALID_VALUES])
uri at speedy.net
More information about the Python-list