DEV Community

Varun Vk
Varun Vk

Posted on

Python type case demystified

Aren't you always bugged by review comments asking to rename a variable in the right casing? Or just curious why all functions in python are in snake case? Well lets jot down all the cases we have and understand how and when we use it according to PEP8 standard. PEP8 standard suggests a set of rules for these cases and is universally accepted and followed.

1. PascalCase

Case where every word is capitalized. Used in json file tags or keys of a dictionary or dataframe columns or class names but never should it be used to name variables or functions.
Examples:

{
    "Name" : "Abcd",
    "Age": 25
} 
# Dictionary
{'Banana': 'Yellow', 'Apple': 'Red'}
# Pandas dataframe
df['BandwidthReported'] = df['Bw'] * 100.

2. camelCase

Case where all words except the first word is capitalized. In python, all the variables should use camelCase.
Examples:

totalCostOfTrips = numOfDays * expensesPerDay

# Naming dictionaries
fruits = {'Banana': 'Yellow', 'Apple': 'Red'}

# When you access the contents of fruits you will use camelCase for the
# variable and Pascal case for the key
print(fruits['Banana'])

3. snake_case

Case where each word is separated by '_' i.e. underscore, you should always use snake case for function names.
Example:

 def hello_world():
    print("Hello World")

4. CAPTIAL_SNAKE_CASE

This case is used only for constants in your functions or class. So any const in python should be named with all capitals and underscore between the words.
Example:

MILLISECONDS_TO_SECONDS = 1000
VERSION = 2.0

Bonus topics

Also all variable and functions which are not exposed and are only for internal use should be named with a leading _, like when using function decorators.

def two_square(a, b):
    def _square(x):
        return x * x;
    return _square(a) + _square(b)

Or in case of function decorators

# Function decorator to time the function call, this decorator can be used for any function.
import time
def timeit(foo):
    def _func(*args, **kwargs):
        startTime = time.time()
        foo(*args, **kwargs)
        endTime = time.time()
        print(f'Time taken to execute: {endTime - startTime} second')
    return _func

@timeit
def two_square(a, b):
    def _square(x):
        return x * x;
    return _square(a) + _square(b)

# Call the function normally
two_square(3, 4)

Function decorators use *args and **kwargs, to know more about these read my other article here

Top comments (0)