Reputation: 843
I am aware that constants in Python are more of a convention yet I got into an argument with a fellow programmer over the following line:
FILE = open("file.txt").readlines()
With FILE
later used multiple times, e.g. in a for line in FILE
We want to code as good as possible. I believe FILE
should never be declared as a constant because it relies on the output of the open()
and readlines()
functions. Yet the counter-argument is that FILE
never changes in our program, so behaves like a constant should. Which one is it?
Exceptions aside, shouldn't it be a variable, i.e. written as a variable according to the naming conventions, so file
in all lowercase?
Upvotes: 0
Views: 175
Reputation: 782427
A constant is not just something that doesn't change over the life of a program run, it's a name for something whose value is predefined, and generally independent of the dynamic state of the application or environment. Typical uses are for things like mathematical constants like PI
, or application parameters like NUMBER_OF_PLAYERS
.
In your example, the value of FILE
is dependent on the contents of the file. It's not a predefined constant, since the file can change from one run of the program to the next.
Another way to look at it is that when you see a use of a constant in the program, you just have to find the initialization of it to know what its value is. But if you initialize the constant from a file, you can't tell what its value will be.
PEP8 doesn't define "constant", so you can do whatever you like, but I think most programmers would find your intended use of FILE
to be confusing or non-idiomatic. Consider that in some programming languages, what you're attempting would not even be possible -- if they have explicit constant
declarations, they require that the value be calculable at compile time.
Upvotes: 2