amontalenti / elements-of-python-style

Goes beyond PEP8 to discuss what makes Python code feel great. A Strunk & White for Python.
3.44k stars 260 forks source link

Avoid numeric literals in code body (suggestion) #12

Closed glenfant closed 8 years ago

glenfant commented 8 years ago

Numeric literals, other than -1, 0 and 1 should never appear in the code body. Use constants, preferably from a config.py like module if you're in a big package, or values used in various modules.

This is not Python specific but I have lost so much time fixing bugs this ugly stuff yields...

# Bad
def is_adult(person):
    return person.age() >= 18

def years_of_adult(person):
    if is_adult(person):
        return person.age() - 18
    return 0

# Good
from config import ADULT_LOW_AGE

def is_adult(person):
    return person.age() >= ADULT_LOW_AGE

def years_of_adult_state(person):
    if is_adult(person):
        return person.age() - ADULT_LOW_AGE
    return 0
amontalenti commented 8 years ago

Thanks for your suggestion, @glenfant.

My take on this is that though a module of constants is a common and perfectly idiomatic thing in Python, I am not sure I am ready to suggest, generally, that numeric literals always be factored out of code. It's the kind of suggestion that, though well-intentioned, could lead to "cargo cult programming", IMO. But I appreciate you raising the issue.

glenfant commented 8 years ago

All is a matter of good balance ;)

amontalenti commented 8 years ago

Thanks again @glenfant -- I'll close this issue since I don't think there are concrete changes to make to the guide based on this thread.