How and Why You Should Be Explicit When Python Coding

and
Posted on Oct 9, 2020

The skills we demoed here can be learned through taking Data Science with Machine Learning bootcamp with NYC Data Science Academy.

In a previous article, you learned how to format your Python code for optimal readability. That piece went into detail about spacing, number of characters on a line, and more. In this article, you will learn how to keep your Python code explicit to ensure others fully understand your work and eliminate any possible confusion. This good practice will also make your code look and read well.

You should always write your code as explicitly as possible. In other words, you should be as literal as you can. This will ensure that there is no room for incorrect interpretation on the side of anyone reading your code, even when that is you.

Naming Conventions

In another article, we discussed common naming conventions. We’re now going to go over how naming conventions overlap with keeping your Python code specific and readable, without any confusion. 

Make sure to choose names that are descriptive and leave no room for incorrect interpretation or ambiguity. 

These aren’t great choices of variable names because they aren’t descriptive enough. 

The function above, called “read,” will read some file in and have different behavior based on the file’s extension. This type of function can easily cause errors. We call this an implicit function because the information from the file extension modifies the code’s behavior. 

Calling this “name” or “full name” is a much better practice than the one used in the previous one. The syntax “first name, last name” is called unpacking, and we can do this to unpack a collection of values into different variables; in this case, we’re unpacking the split elements of this string. We now have much more interpretable names for these values.

The name in this example is followed by explicit functions. “read_csv” and “read_json” are explicit functions, and they are specific for each type of data that we are trying to read. This can be easier for the user because the names make everything much clearer about what’s going on.

Calling objects from modules and packages

Another opportunity for using explicit rather than implicit syntax is how you should refer to objects imported from modules and packages. You should refer to a module when calling a function, class, or object from that module.

You’re able to import every single object within a module or package if you would like to, like in the example above, by using the import statement: from module import *. However, this is generally frowned upon because there can be name conflicts with existing objects in your namespace. There is no warning that your variables will be overwritten! When in doubt, it’s better to call the objects from the correct module or package explicitly.

For modules with very long names that you don’t want to write out repeatedly, you can use an alias to shorten the module or package name. Two good examples are the numpy (np) and pandas (pd) aliases, which are used universally. You can decide on your own aliases for other modules and packages. 

Keeping your Python code explicit and specific is extremely important. Working these best practices into your daily coding will not only help strengthen your coding abilities, but it will also keep your code organized. This makes it easy for others to interpret what you’re trying to express.

All we’ve discussed today is just the beginning of keeping your code readable and interpretable. Readability in Python code is routinely stressed in our bootcamps and programs. 

Ready to advance your programming skills to the next level? 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 data science bootcamps.

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 >

Leave a Comment

No comments found.

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