Skip to main content
  1. Data Science Blog/

Python Naming Convention

·465 words·3 mins· loading · ·
Python Software Development Programming Python Programming Software Development Best Practices Best Practices Software Development

On This Page

Table of Contents
Share with :

Python Naming Convention

Python Naming Convention
#

  • UPPERCASE / UPPER_CASE_WITH_UNDERSCORES => module-level constants
  • lowercase / lower_case_with_underscores => for variable and function name.
  • CapitalizedWords (or CapWords, or CamelCase – so named because of the bumpy look of its letters [4]). This is also sometimes known as StudlyCaps. => CamelCase => Class
    • Note: When using acronyms in CapWords, capitalize all the letters of the acronym. Thus HTTPServerError is better than HttpServerError.
  • mixedCase (differs from CapitalizedWords by initial lowercase character!)
  • Capitalized_Words_With_Underscores (ugly!)
  • _single_leading_underscore: weak “internal use” indicator. E.g. from M import * does not import objects whose names start with an underscore.
  • singletrailing_underscore: used by convention to avoid conflicts with Python keyword, e.g. tkinter.Toplevel(master, class_=‘ClassName’)
  • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, boo becomes _FooBarboo; see below).
  • __double_leading_and_trailing_underscore**: “magic” objects or attributes that live in user-controlled namespaces. E.g. __init**, __import** or __file**. Never invent such names; only use them as documented.
  • Never use the characters ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single character variable names.

Programming Recommendations
#

Use “is not” operator
#

  • Correct:
if foo is not None:
  • Wrong:
if not foo is None:

Always use a def statement
#

  • Correct:
def f(x): return 2*x
  • Wrong:
f = lambda x: 2*x

all try/except clauses
#

  • Correct:
try:
    value = collection[key]
except KeyError:
    return key_not_found(key)
else:
    return handle_value(value)
  • Wrong:
try:
    # Too broad!
    return handle_value(collection[key])
except KeyError:
    # Will also catch KeyError raised by handle_value()
    return key_not_found(key)

Context managers should be invoked through separate functions or methods
#

  • Correct:
with conn.begin_transaction():
    do_stuff_in_transaction(conn)
  • Wrong:
with conn:
    do_stuff_in_transaction(conn)

Be consistent in return statements
#

  • Correct:
def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0:
        return None
    return math.sqrt(x)
  • Wrong:
def foo(x):
    if x >= 0:
        return math.sqrt(x)

def bar(x):
    if x < 0:
        return
    return math.sqrt(x)

startswith, endswith
#

  • Use ‘’.startswith() and ‘’.endswith() instead of string slicing to check for prefixes or suffixes.
  • Correct: if foo.startswith(‘bar’):
  • Wrong: if foo[:3] == ‘bar’:

Object type comparisons
#

  • Correct: if isinstance(obj, int):
  • Wrong: if type(obj) is type(1):

Sequences, (strings, lists, tuples)
#

-For sequences, (strings, lists, tuples), use the fact that empty sequences are false:

  • Correct:
if not seq:
	if seq:
  • Wrong:
if len(seq):
	if not len(seq):

boolean value comparision
#

Don’t compare boolean values to True or False using ==:

  • Correct: if greeting:
  • Wrong: if greeting == True:
  • Worse: if greeting is True:

Assignment
#

If an assignment has a right hand side, then the equality sign should have exactly one space on both sides:

  • Correct:
code: int

class Point:
    coords: Tuple[int, int]
    label: str = '<unknown>'
  • Wrong:
code:int  # No space after colon
code : int  # Space before colon

class Test:
    result: int=0  # No spaces around equality sign

References
#

Dr. Hari Thapliyaal's avatar

Dr. Hari Thapliyaal

Dr. Hari Thapliyal is a seasoned professional and prolific blogger with a multifaceted background that spans the realms of Data Science, Project Management, and Advait-Vedanta Philosophy. Holding a Doctorate in AI/NLP from SSBM (Geneva, Switzerland), Hari has earned Master's degrees in Computers, Business Management, Data Science, and Economics, reflecting his dedication to continuous learning and a diverse skill set. With over three decades of experience in management and leadership, Hari has proven expertise in training, consulting, and coaching within the technology sector. His extensive 16+ years in all phases of software product development are complemented by a decade-long focus on course design, training, coaching, and consulting in Project Management. In the dynamic field of Data Science, Hari stands out with more than three years of hands-on experience in software development, training course development, training, and mentoring professionals. His areas of specialization include Data Science, AI, Computer Vision, NLP, complex machine learning algorithms, statistical modeling, pattern identification, and extraction of valuable insights. Hari's professional journey showcases his diverse experience in planning and executing multiple types of projects. He excels in driving stakeholders to identify and resolve business problems, consistently delivering excellent results. Beyond the professional sphere, Hari finds solace in long meditation, often seeking secluded places or immersing himself in the embrace of nature.

Comments:

Share with :

Related

What is a Digital Twin?
·805 words·4 mins· loading
Industry Applications Technology Trends & Future Computer Vision (CV) Digital Twin Internet of Things (IoT) Manufacturing Technology Artificial Intelligence (AI) Graphics
What is a digital twin? # A digital twin is a virtual representation of a real-world entity or …
Frequencies in Time and Space: Understanding Nyquist Theorem & its Applications
·4103 words·20 mins· loading
Data Analysis & Visualization Computer Vision (CV) Mathematics Signal Processing Space Exploration Statistics
Applications of Nyquists theorem # Can the Nyquist-Shannon sampling theorem applies to light …
The Real Story of Nyquist, Shannon, and the Science of Sampling
·1146 words·6 mins· loading
Technology Trends & Future Interdisciplinary Topics Signal Processing Remove Statistics Technology Concepts
The Story of Nyquist, Shannon, and the Science of Sampling # In the early days of the 20th century, …
BitNet b1.58-2B4T: Revolutionary Binary Neural Network for Efficient AI
·2637 words·13 mins· loading
AI/ML Models Artificial Intelligence (AI) AI Hardware & Infrastructure Neural Network Architectures AI Model Optimization Language Models (LLMs) Business Concepts Data Privacy Remove
Archive Paper Link BitNet b1.58-2B4T: The Future of Efficient AI Processing # A History of 1 bit …
Ollama Setup and Running Models
·1753 words·9 mins· loading
AI and NLP Ollama Models Ollama Large Language Models Local Models Cost Effective AI Models
Ollama: Running Large Language Models Locally # The landscape of Artificial Intelligence (AI) and …