When is a variable considered constant in terms of PEP8 naming styles?

大兔子大兔子 提交于 2020-01-13 11:11:23

问题


In keeping with PEP8 conventions, in a .py I can define constants as:

NAME = "Me"
AGE = "Old"
GENER = "Male"

If a .txt contained Me Old Male on a single line, and in another .py I performed:

FILE = "C:/path/to/file.txt"  # a declared constant, easy
with open(FILE, 'r') as f:
    content = f.read().rstrip('\n').split()
    data = ','.join(content)  # returns Me,Old,Male

Question(s):

Can content and data be considered constants?

To be constant, must a variable be declared as a constant at build?

Or is constant vice variable a function of the ability to be altered by user input in runtime?

Supporting Informaton:

content is what is in the file, but it is subject to .rstrip() and .split() but it as a whole is never changed later. data is made from content, which hasn't changed and wont, and is subject to .join(). Neither values change after they are initialized.

I would view this similar to:

>>> A = 2  # a declared constant
>>> B = 2  # another declared constant
>>> TOTAL = A + B  # 'caps' per PEP8 for constant naming
4

Assuming the program has terminated and TOTAL is never altered, I would consider this value a constant. Again under the presumption that any variable that is not alterable during runtime is to be considered a constant.

Feel free to alter my notions as required to align with standards!


回答1:


If you are going to treat the value as a constant in the rest of your code, by all means, use CONSTANT_CASE for those globals. It's up to you, it's merely a documentation convention.

In other words, it's a convention that aims to make it easier for future readers of your code to understand that the value of such a global is set just once and is expected not to change over the lifetime of the program.

Note that I'd generally try to avoid loading file data on module import; it makes it harder to test and impacts performance. Load that data on first use instead (using a function).




回答2:


I think you are confounding notions of constant variables with actual data held in a file. Python does not really have a notion of constants like C or Java do. Thus, the notation of declaring constant variables with upper-cased variable names is only a convention to tell the programmer (you), that you are dealing with a variable that shouldn't be changed, but that python won't restrict you from doing so.

The only way that I can think of, to a "real" constant is to make it an attribute in a class, and restrict the __setattr__:

class Constant:
    def __init__(self, name, age, gender):
        self.__dict__["NAME"] = name
        self.__dict__["AGE"] = age
        self.__dict__["Gender"] = gender

    def __setattr__(self, a, v):
        raise TypeError("Cannot set attributes of '{}' class".format(str(self.__class__).rsplit('.',1)[1]))

Thus, you can read the attributes, but won't be able to set them:

In [131]: c = Constant("Me", "Old", "Male")

In [132]: c.NAME
Out[132]: 'Me'

In [133]: c.NAME = 'd'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-133-d979661dfd1d> in <module>()
----> 1 c.NAME = 'd'

<ipython-input-130-9a8604514ac4> in __setattr__(self, a, v)
      6 
      7     def __setattr__(self, a, v):
----> 8         raise TypeError("Cannot set attributes of '{}' class".format(str(self.__class__).rsplit('.',1)[1]))

TypeError: Cannot set attributes of 'Constant'>' class


来源:https://stackoverflow.com/questions/44636868/when-is-a-variable-considered-constant-in-terms-of-pep8-naming-styles

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