Python sequence naming convention

拟墨画扇 提交于 2020-01-14 13:49:32

问题


Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. Of course, I went through the famous PEP8, and made some research on google, and it seems that the accepted convention is to add the letter "s" at the end of the variable name.

Let's assume we have a sequence of "weight values", therefore the variable name for the sequence should be weights. So far that's fine, but there will be cases where some word ends with "s" and happen to be the more logical way to name a variable which is not a sequence. Or let's say you have sequences of weights themselves stored into a sequence. The "s" naming convention would name the variable weightss, which is ugly. I am sure there is be a better naming convention for sequences.

What naming convention for sequences would you advise?


回答1:


In general, avoid this kind of behaviour. Notice from PEP8

A Foolish Consistency is the Hobgoblin of Little Minds

which is exactly what calling a variable weightss would be doing. So in general have your variables describing what they are, not according to some naming convention:

weights = [44, 66, 88]
weight_groups = [[44, 66, 88], ...]

etc.

From the same section of the PEP8:

But most importantly: know when to be inconsistent -- sometimes the style guide just doesn't apply. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask!




回答2:


The "s" naming convention would name the variable weightss, which is ugly. I am sure there is be a better naming convention for sequences.

I think the convention you're describing is meant to be interpreted as "whenever you have list of something, make it clear that it's a list by pluralizing it". For example, if you have a list of instances of grass, you would call this grasses, not grasss. I don't think it's meant to be taken as literally as you're taking it.

PEP always advises you to take your own approach if that is more readable and useful. As Ali mentioned, one of the guiding principles of PEP is that you shouldn't fall prey to foolish consistencies.




回答3:


Whatever you little heart desires....

Just kidding, but I wouldn't get to hung up on it. If it's ugly, do something to make it more readable like seq_weight and seq_weights




回答4:


Why not just thing_list or thing_seq?



来源:https://stackoverflow.com/questions/659415/python-sequence-naming-convention

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!