Given that there are no real constants in Python, the convention is to name them in CAPS for conveying the intentions.
In following sample code, FIRST
and SECOND
are constants:
def fibonacci_generator(count):
FIRST, SECOND = 0, 1
a, b = FIRST, SECOND
for _ in range(count):
yield a
a, b = b, a + b
print(list(fibonacci_generator(10)))
But for the two constants, PyCharm is giving warning as:
Variable in function should be lowercase
Is there any other correct way to define constants within functions? (Without suppressing the PyCharm warning)
However, Python doesn't have a dedicated syntax for defining constants. In practice, Python constants are just variables that never change. To prevent programmers from reassigning a name that's supposed to hold a constant, the Python community has adopted a naming convention: use uppercase letters.
In python, a function is a logical unit of code containing a sequence of statements indented under a name given using the “def” keyword. In python def keyword is the most used keyword. Use of def keyword: In the case of classes, the def keyword is used for defining the methods of a class.
A constant is a type of variable that holds values, which cannot be changed. In reality, we rarely use constants in Python. Constants are usually declared and assigned on a different module/file. Then, they are imported to the main file.
The global keyword in Python is used to modify a global variable in a local context (as explained here). This means that if the op modifies SOME_CONSTANT within myfunc the change will affect also outside the function scope (globally).
According to PEP8 constants should be defined at the module level:
Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include
MAX_OVERFLOW
andTOTAL
.
There is no convention for naming constants inside functions or methods.
You can:
In this case, you could also use default arguments without getting a warning but it does seem like an overkill just to get around a PEP8 convention warning:
However, this is counter-productive because you violate one convention in order to not get a warning about violating another.
Besides what have been proposed by @DeepSpace, other potential choices are (1) using underscore-prefixed variable names such as _FIRST
, _SECOND
, etc.; (2) writing a class instead and make the constants class-level constants.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With