Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Course
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM Tools
Machine Learning
Machine Learning & AI
Machine Learning Tools
Manage Data
MLOps
Natural Language Processing
Newsletter Archive
NumPy
Pandas
Polars
PySpark
Python Helpers
Python Tips
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

Python Tips

A Function Should Only Do One Task

A function should do only one task, not multiple tasks. The function process_data tries to do multiple tasks such as adding new features, adding one, and taking a sum of all columns. Using comments helps explain each block of code, but it takes a lot of work to keep the comments up-to-date. It is also difficult to test each unit of code inside a function.

A better practice is to split the function process_data into smaller functions that do only one thing. In the code below, I split the function process_data into 4 different functions and apply these functions to a pandas DataFrame in order using pipe.

My previous tips on good Python practices.

A Function Should Only Do One Task Read More »

Avoid Duplication in Your Code

While writing code, we should avoid duplication because:

It is redundant

If we make a change to one piece of code, we need to remember to make the same change to another piece of code. Otherwise, we will introduce bugs into our code.

In the code above, we use the filter X['date'] > date(2021, 2, 8) twice. To avoid duplication, we can assign the repeated code to a variable or a function.

My previous tips on good Python practices.

Avoid Duplication in Your Code Read More »

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran