Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pep8

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!

like image 711
madeslurpy Avatar asked Jun 19 '17 17:06

madeslurpy


1 Answers

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).

like image 154
Martijn Pieters Avatar answered Nov 14 '22 21:11

Martijn Pieters