Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I capitalize constant in Python?

Tags:

python

In PEP8, the general rule is to declare constants in UPPER_CASE chars. In real life, there can be a number of situations:

#!env python

DATABASE_HOST = 'localhost'
app = Flask('myapp')
base_two = partial(int, base=2) 

Typically we consider string-type or numeric-type variables as immutable and thus constants, but not object or function. The problem is there is no-way a linter can do type-checking.

How do you deal with this case? Should I capitalize them or just disable this rule in my linter?

like image 889
boh Avatar asked Jun 11 '18 09:06

boh


People also ask

Should constants be capitalized?

"Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters." According to MDN: NOTE: Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters."

How do you write a constant in Python?

Python doesn't have built-in constant types. By convention, Python uses a variable whose name contains all capital letters to define a constant.

Should you use constants in Python?

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.

What is capitalized in Python?

Python String capitalize() The capitalize() method converts the first character of a string to an uppercase letter and all other alphabets to lowercase.


Video Answer


1 Answers

Personally the only time I ever capitalise something is when providing a value externally that should never be changed. Otherwise, it's find to leave it in lowercase, especially if the value is just part of the logic flow. so

FLAG = object()

def func(arg_with_default = FLAG):
    if arg_with_default is FLAG:
         do_default()
    else:
         do_something_else(arg_with_default)

I think you're confusing immutability with constants.

t = (1, 2)
t[0] = 3  # error -- immutable
t = 3.14  # fine -- not constant

Python has no concept of constants. Every variable can be overridden, hence why in cases where it matters that a variable is not changed, that is perhaps the time to make that obvious by using capitalisation.

If the linter is complaining that you aren't capitalising things that don't need to be, I'd disable that option.

like image 56
FHTMitchell Avatar answered Oct 07 '22 07:10

FHTMitchell