Best Naming Conventions: Python Code

Posted on Sep 8, 2020
The skills I demoed here can be learned through taking Data Science with Machine Learning bootcamp with NYC Data Science Academy.

Naming Conventions 

During a recent workshop, bootcamp instructor Alex Baransky shared some of the best practices in writing Python code for better readability. Through this series of articles, we will summarize and give you a few examples of those best practices to help you write more elegant Python code, benefiting those who may read and use your code in the future, including yourself.

Python is an object-oriented programming language. This means you’ll create, name, and use all kinds of objects in any given Python project. Naming conventions are the rules of thumb for naming the objects that you create. Understanding these conventions is the first step to keeping your code readable for you and your teammates. 

Through our bootcamps and courses, we share to students that there are tons of ways to name objects, some being better than others. Understanding the difference between good and great is the way to impress prospective employers and peers. In this article, we will share best practices in naming conventions that you can follow and adopt when writing your Python code.

Basic Naming Conventions

Let’s start with the most common options for naming objects in Python. The following are basic ways to name: 

  • Single lowercase
    • Often used for local variables in functions, such as x or i
  • Single uppercase
    • Often used to name matrices
  • Lowercase word
    • The most frequent naming convention for the widest variety of objects
  • Lowercase word with underscores
    • Same uses as Lowercase word, but for more complicated names
  • Uppercase word
    • Used for single-word static variables
  • Uppercase word with underscores
    • Used for multi-word static variables
  • Capitalized words (aka CapWords or CamelCase)
    • This is where each word is capitalized, and there are no spaces or underscores between them
    • Used for naming classes (even if the name is just a single, capitalized word)
  • Mixed Case
    • This is where you start with a lowercase word followed by every other word capitalized
    • This convention is predominantly used in Java and less in Python 

Each of these options has different use cases. They are not only for aesthetics, but each option also helps you create meaningful objects in your code. 

Names to Avoid

Just as there are things you should do, there are things you shouldn’t. These are conventions you will want to avoid when writing Python code. 

  • Lowercase letter “el” - instead, use a capital letter “L”
  • Uppercase letter “oh” - “O” 
  • Uppercase letter “eye” - “I”

We avoid those names because in some fonts, they are indistinguishable from the numbers “1” and “0”, which makes it difficult for the user to understand what’s going on.

You should also avoid using Python keywords and built-in class/function names for your variable names. For example, words like “max,” “sum,” “class,” and “list” are words that already exist in any Python environment. Therefore, to use them for something other than their function could make things messy and confusing.

Modules and Packages

A module is a collection of pre-built functions and other objects used to perform certain tasks. Modules should have short, lowercase names. Underscores can be used in the module name if it improves readability (like for names with multiple words). 

Packages are like directories that contain modules and other objects. Python packages should follow the same convention, although the use of underscores in package names is discouraged. 

Variables and Functions

Do you know the difference between a function and a method?To understand the difference, think of the square-rectangle relationship: a method is a function, but not all functions are methods. A method is a special type of function that belongs to a class. Only objects of that class type can use these special functions. This is part of the object-oriented paradigm of Python and can help improve the organization and readability of our code. In Python, the names of variables and functions should be lowercase. Individual words can be separated by underscores when needed. This will improve readability within your code. Method names should follow the same conventions as function names. 

Here are a few best practices to follow when naming your variables and functions:

  • Constants should be represented by all capital letters and separated by underscores when needed 
  • Use names that are representative of the meaning of the object rather than meaningless, single-character names
  • Names i, j, and k should be reserved for representing index values

Understanding and adopting these best practices is a great way to polish your coding skills. Writing more elegant code will not only impress your current colleagues, but it will also help you build better coding habits that may catch the attention of future employers. 

Ready to advance your programming skills? Check out this three-course program focused on building and advancing your Python Programming skills, or start your journey towards data science mastery by enrolling in our upcoming remote live and online bootcamps this Fall. 

About Authors

Alex Baransky

Alex graduated from Columbia University with training in natural and technical sciences. He enjoys finding ways to utilize data science to answer questions efficiently and to improve the interpretability of results. Alex takes pride in his ability to...
View all posts by Alex Baransky >

Related Articles

Leave a Comment

How to Properly Document Your Python Code – The Data Sciences Niche Domain News October 4, 2020
[…] you learned about the best practices that you can follow on naming conventions for better readability of your Python code. In this article, you will learn how you can create […]

View Posts by Categories

Our Recent Popular Posts

View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI