Why doesn't a dictionary work in classes?

אורי uri at speedy.net
Wed Dec 26 00:10:32 EST 2018


Hi,

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.
https://stackoverflow.com/questions/53924235/why-doesnt-a-dictionary-work-in-classes

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[0] 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
https://github.com/speedy-net/speedy-net/tree/uri_change_settings_2018-12-25_a
- for example this code is on
https://github.com/speedy-net/speedy-net/blob/uri_change_settings_2018-12-25_a/speedy/core/accounts/models.py

אבי (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
usually written.

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
identical:

        self.assertListEqual(list1=User.ALL_GENDERS,
list2=[User.GENDERS_DICT[gender] for gender in User.GENDER_VALID_VALUES])
        self.assertListEqual(list1=User.ALL_GENDERS,
list2=[User.GENDER_FEMALE_STRING, User.GENDER_MALE_STRING,
User.GENDER_OTHER_STRING])
        self.assertListEqual(list1=User.ALL_GENDERS, list2=['female',
'male', 'other'])


Thanks,
אורי (Uri)
uri at speedy.net


More information about the Python-list mailing list