Code Formatting In Python With Black - Python Tutorial

Patrick Loeber · Beginner ·🛠️ AI Tools & Apps ·5y ago

Key Takeaways

The video demonstrates the use of the Black tool for automatic code formatting in Python, showcasing its installation, usage, and configuration options, as well as its integration with version control systems like Git.

Full Transcript

do you think this is the best way to format your python code or this or maybe even this what's up everyone if you're new to the channel i'm patrick and i do weekly videos on python and machine learning related topics and if you follow my tutorials then you should know that i do care about code formatting and having a nice and clean code so why did i say in the title that i don't care and the reason is i don't care about code formatting while i'm writing code instead i use a tool that is doing this automatically for me so i can save time and energy and focus on the more important things so in this video i want to show you this tool and maybe i convince you to use this tool as well it's actually pretty simple so the tool i'm using is called black and you can find it on github and it tells us it's the uncompromising python code formatter and it's actually in the repo of the official python software foundation so even they recommend to use this and if you have a look at the readme then it tells us it's the uncompromising python code formatter by using it you agree to see control over minutiae of hand formatting i actually had to google it so it means we see control over details of our code formatting and in return black gives you speed determinism and freedom from pi code style nagging about formatting you will save time and mental energy for more important matters so no longer discussing or fighting with your colleagues what's the best code style instead you just run this code and there are no compromises and then you have a nice formatted code and i actually like this code format that black is enforcing and if we scroll down to the used by section then we can see that black is used in a lot of open source projects and also by the following organizations like facebook dropbox mozilla and quora so a lot of people trust this tool and so do i now in order to install and use this we just have to say pip install black and then to use it we can say black and then we can either use a single python file or a whole directory and then it's formatting the whole directory and there is a list of command line options but actually the only one that lets you configure and change the code style is the minus minus line length command with this you can change the characters per line to allow so that default is 88 and this is actually the only thing that you can change and configure that affects the code styling and everything else is fixed and no compromises here so here i'm in my editor and i prepared an example file that i want to edit with black in a second so you can see i have a function then i have a list where i didn't know where i should start a new line and the same with a dictionary and then we have this function from the beginning and now here you can see some parts of the code are already underlined so here my editor pycharm is already clever enough to detect these minor issues so if i hover over this with the mouse then you should see the hint it expected two blank lines found zero after the importing and also here for the comment if i hover over this then we see at least two spaces before inline comment and then also at the very end we have a small underline here so if i hover over this then we see no new line at the end of the file so according to the python style guide you should always end your file with a new line so these are all minor issues with my code formatting but i actually don't care about them while i'm writing the code instead afterwards i use my terminal and here i already said pip install black and then i say black and then the file name so in this case it's called example.pi and now i will run this and then notice what happens to the file alright so the formatting happens in the terminal we can see all done one file reformatted so now let's have a look so here you can see that after the import statement we have two blank lines then we have our function then again we have two blank lines then for this list it detected that this is short enough to be put into one single line but not for this dictionary here for this it used separate lines and also for this function it used a separate line for each argument and then we have at the very end we can also see that we have a new blank line at the end so now all is good and we don't have anything underlined as well in pycharm so yeah this is actually everything you need so you don't have to care about the code formatting and then just run black and your file name or the whole directory and you're good to go so i want to mention one more thing in our code you see that the logging is unused that's why it's appearing slightly more dark and also for this function argument this is not used but black does not remove the unused code so this is not what black is doing it's not changing your code it's only changing the code formatting so this is very important and i wanted to make this clear here and now i want to show you one more trick so you don't even have to run black yourself you can automate this as well so if we go back to the readme of black and scroll down there we can find the section version control integration so if you use git in your project then you can use this pre commit hook so you just install this and then you put this in a file that is called dot pre-commit config.yml and you put this in your repository and then you write these commands here and then what happens is whenever you commit your changes it will automatically apply black to all the files and then you have a nice code formatting without even running it manually so this is pretty cool and then when you upload it to github then you have a nice formatted code so you can use this as a pre-commit hook and this is actually what i recommend then you can see the changes already locally before pushing it but you can also run this as a github action for example you can define this for each push or pull request and then it's running black automatically for you whenever you push or make a pull request so yeah i recommend to try it out see if you like it and if you can save some time with it and yeah i hope you enjoyed this tutorial and then i hope to see you in the next video bye you

Original Description

Learn how to use the black tool for code formatting in Python. Stop wasting time to determine the best format, and just let "black" do the code formatting for you automatically. Repo: https://github.com/psf/black Get my Free NumPy Handbook: https://www.python-engineer.com/numpybook ✅ Write cleaner code with Sourcery, instant refactoring suggestions in VS Code & PyCharm: https://sourcery.ai/?utm_source=youtube&utm_campaign=pythonengineer * ⭐ Join Our Discord : https://discord.gg/FHMg9tKFSN 📓 ML Notebooks available on Patreon: https://www.patreon.com/patrickloeber If you enjoyed this video, please subscribe to the channel: ▶️ : https://www.youtube.com/channel/UCbXgNpp0jedKWcQiULLbDTA?sub_confirmation=1 ~~~~~~~~~~~~~~~ CONNECT ~~~~~~~~~~~~~~~ 🖥️ Website: https://www.python-engineer.com 🐦 Twitter - https://twitter.com/patloeber ✉️ Newsletter - https://www.python-engineer.com/newsletter 📸 Instagram - https://www.instagram.com/patloeber 🦾 Discord: https://discord.gg/FHMg9tKFSN ▶️ Subscribe: https://www.youtube.com/channel/UCbXgNpp0jedKWcQiULLbDTA?sub_confirmation=1 ~~~~~~~~~~~~~~ SUPPORT ME ~~~~~~~~~~~~~~ 🅿 Patreon - https://www.patreon.com/patrickloeber #Python Timeline: 00:00 - Introduction 00:44 - Black Overview 02:38 - Black Example 05:25 - Version Control Integration ---------------------------------------------------------------------------------------------------------- * This is an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you so much for the support! 🙏
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Patrick Loeber · Patrick Loeber · 0 of 60

← Previous Next →
1 Lists in Python - Advanced Python 01 - Programming Tutorial
Lists in Python - Advanced Python 01 - Programming Tutorial
Patrick Loeber
2 Tuples in Python - Advanced Python 02 - Programming Tutorial
Tuples in Python - Advanced Python 02 - Programming Tutorial
Patrick Loeber
3 Dictionaries in Python - Advanced Python 03 - Programming Tutorial
Dictionaries in Python - Advanced Python 03 - Programming Tutorial
Patrick Loeber
4 Sets in Python - Advanced Python 04 - Programming Tutorial
Sets in Python - Advanced Python 04 - Programming Tutorial
Patrick Loeber
5 Strings in Python - Advanced Python 05 - Programming Tutorial
Strings in Python - Advanced Python 05 - Programming Tutorial
Patrick Loeber
6 Collections in Python - Advanced Python 06 - Programming Tutorial
Collections in Python - Advanced Python 06 - Programming Tutorial
Patrick Loeber
7 Itertools in Python - Advanced Python 07 - Programming Tutorial
Itertools in Python - Advanced Python 07 - Programming Tutorial
Patrick Loeber
8 Lambda in Python - Advanced Python 08 - Programming Tutorial - Map Filter Reduce
Lambda in Python - Advanced Python 08 - Programming Tutorial - Map Filter Reduce
Patrick Loeber
9 Exceptions in Python - Advanced Python 09 - Programming Tutorial
Exceptions in Python - Advanced Python 09 - Programming Tutorial
Patrick Loeber
10 Logging in Python - Advanced Python 10 - Programming Tutorial
Logging in Python - Advanced Python 10 - Programming Tutorial
Patrick Loeber
11 JSON in Python - Advanced Python 11 - Programming Tutorial
JSON in Python - Advanced Python 11 - Programming Tutorial
Patrick Loeber
12 Random Numbers in Python - Advanced Python 12 - Programming Tutorial
Random Numbers in Python - Advanced Python 12 - Programming Tutorial
Patrick Loeber
13 Decorators in Python - Advanced Python 13 - Programming Tutorial
Decorators in Python - Advanced Python 13 - Programming Tutorial
Patrick Loeber
14 Generators in Python - Advanced Python 14 - Programming Tutorial
Generators in Python - Advanced Python 14 - Programming Tutorial
Patrick Loeber
15 Threading vs Multiprocessing in Python - Advanced Python 15 - Programming Tutorial
Threading vs Multiprocessing in Python - Advanced Python 15 - Programming Tutorial
Patrick Loeber
16 Threading in Python - Advanced Python 16 - Programming Tutorial
Threading in Python - Advanced Python 16 - Programming Tutorial
Patrick Loeber
17 Multiprocessing in Python - Advanced Python 17 - Programming Tutorial
Multiprocessing in Python - Advanced Python 17 - Programming Tutorial
Patrick Loeber
18 Function arguments in detail - Advanced Python 18 - Programming Tutorial
Function arguments in detail - Advanced Python 18 - Programming Tutorial
Patrick Loeber
19 The asterisk (*) operator in Python - Advanced Python 19 - Programming Tutorial
The asterisk (*) operator in Python - Advanced Python 19 - Programming Tutorial
Patrick Loeber
20 Shallow vs Deep Copying in Python - Advanced Python 20 - Programming Tutorial
Shallow vs Deep Copying in Python - Advanced Python 20 - Programming Tutorial
Patrick Loeber
21 Context Managers in Python - Advanced Python 21 - Programming Tutorial
Context Managers in Python - Advanced Python 21 - Programming Tutorial
Patrick Loeber
22 KNN (K Nearest Neighbors) in Python - Machine Learning From Scratch 01 - Python Tutorial
KNN (K Nearest Neighbors) in Python - Machine Learning From Scratch 01 - Python Tutorial
Patrick Loeber
23 Linear Regression in Python - Machine Learning From Scratch 02 - Python Tutorial
Linear Regression in Python - Machine Learning From Scratch 02 - Python Tutorial
Patrick Loeber
24 Logistic Regression in Python - Machine Learning From Scratch 03 - Python Tutorial
Logistic Regression in Python - Machine Learning From Scratch 03 - Python Tutorial
Patrick Loeber
25 Linear and Logistic Regression in 60 lines of Python - Machine Learning From Scratch 04
Linear and Logistic Regression in 60 lines of Python - Machine Learning From Scratch 04
Patrick Loeber
26 Naive Bayes in Python - Machine Learning From Scratch 05 - Python Tutorial
Naive Bayes in Python - Machine Learning From Scratch 05 - Python Tutorial
Patrick Loeber
27 Perceptron in Python - Machine Learning From Scratch 06 - Python Tutorial
Perceptron in Python - Machine Learning From Scratch 06 - Python Tutorial
Patrick Loeber
28 SVM (Support Vector Machine) in Python - Machine Learning From Scratch 07 - Python Tutorial
SVM (Support Vector Machine) in Python - Machine Learning From Scratch 07 - Python Tutorial
Patrick Loeber
29 Decision Tree in Python Part 1/2 - Machine Learning From Scratch 08 - Python Tutorial
Decision Tree in Python Part 1/2 - Machine Learning From Scratch 08 - Python Tutorial
Patrick Loeber
30 Decision Tree in Python Part 2/2 - Machine Learning From Scratch 09 - Python Tutorial
Decision Tree in Python Part 2/2 - Machine Learning From Scratch 09 - Python Tutorial
Patrick Loeber
31 Random Forest in Python - Machine Learning From Scratch 10 - Python Tutorial
Random Forest in Python - Machine Learning From Scratch 10 - Python Tutorial
Patrick Loeber
32 PCA (Principal Component Analysis) in Python - Machine Learning From Scratch 11 - Python Tutorial
PCA (Principal Component Analysis) in Python - Machine Learning From Scratch 11 - Python Tutorial
Patrick Loeber
33 K-Means Clustering in Python - Machine Learning From Scratch 12 - Python Tutorial
K-Means Clustering in Python - Machine Learning From Scratch 12 - Python Tutorial
Patrick Loeber
34 Anaconda Tutorial - Installation and Basic Commands
Anaconda Tutorial - Installation and Basic Commands
Patrick Loeber
35 PyTorch Tutorial 01 - Installation
PyTorch Tutorial 01 - Installation
Patrick Loeber
36 PyTorch Tutorial 02 - Tensor Basics
PyTorch Tutorial 02 - Tensor Basics
Patrick Loeber
37 PyTorch Tutorial 03 - Gradient Calculation With Autograd
PyTorch Tutorial 03 - Gradient Calculation With Autograd
Patrick Loeber
38 PyTorch Tutorial 04 - Backpropagation - Theory With Example
PyTorch Tutorial 04 - Backpropagation - Theory With Example
Patrick Loeber
39 PyTorch Tutorial 05 - Gradient Descent with Autograd and Backpropagation
PyTorch Tutorial 05 - Gradient Descent with Autograd and Backpropagation
Patrick Loeber
40 PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer
PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer
Patrick Loeber
41 PyTorch Tutorial 07 - Linear Regression
PyTorch Tutorial 07 - Linear Regression
Patrick Loeber
42 PyTorch Tutorial 08 - Logistic Regression
PyTorch Tutorial 08 - Logistic Regression
Patrick Loeber
43 PyTorch Tutorial 09 - Dataset and DataLoader - Batch Training
PyTorch Tutorial 09 - Dataset and DataLoader - Batch Training
Patrick Loeber
44 PyTorch Tutorial 10 - Dataset Transforms
PyTorch Tutorial 10 - Dataset Transforms
Patrick Loeber
45 Download Images With Python Automatically - Python Web Scraping Tutorial
Download Images With Python Automatically - Python Web Scraping Tutorial
Patrick Loeber
46 PyTorch Tutorial 11 - Softmax and Cross Entropy
PyTorch Tutorial 11 - Softmax and Cross Entropy
Patrick Loeber
47 Select Movies with Python - Web Scraping Tutorial
Select Movies with Python - Web Scraping Tutorial
Patrick Loeber
48 PyTorch Tutorial 12 - Activation Functions
PyTorch Tutorial 12 - Activation Functions
Patrick Loeber
49 List Comprehension in Python - A Python Feature You MUST KNOW - Python Tutorial
List Comprehension in Python - A Python Feature You MUST KNOW - Python Tutorial
Patrick Loeber
50 PyTorch Tutorial 13 - Feed-Forward Neural Network
PyTorch Tutorial 13 - Feed-Forward Neural Network
Patrick Loeber
51 How To Add A Progress Bar In Python With Just One Line - Python Tutorial
How To Add A Progress Bar In Python With Just One Line - Python Tutorial
Patrick Loeber
52 PyTorch Tutorial 14 - Convolutional Neural Network (CNN)
PyTorch Tutorial 14 - Convolutional Neural Network (CNN)
Patrick Loeber
53 The Walrus Operator - New in Python 3.8 - Python Tutorial
The Walrus Operator - New in Python 3.8 - Python Tutorial
Patrick Loeber
54 PyTorch Tutorial 15 - Transfer Learning
PyTorch Tutorial 15 - Transfer Learning
Patrick Loeber
55 YouTube Data API Tutorial with Python - Analyze Channel Statistics - Part 1
YouTube Data API Tutorial with Python - Analyze Channel Statistics - Part 1
Patrick Loeber
56 YouTube Data API Tutorial with Python - Find Channel Videos - Part 2
YouTube Data API Tutorial with Python - Find Channel Videos - Part 2
Patrick Loeber
57 YouTube Data API Tutorial with Python - Get Video Statistics - Part 3
YouTube Data API Tutorial with Python - Get Video Statistics - Part 3
Patrick Loeber
58 YouTube Data API Tutorial with Python - Analyze the Data - Part 4
YouTube Data API Tutorial with Python - Analyze the Data - Part 4
Patrick Loeber
59 AdaBoost in Python - Machine Learning From Scratch 13 - Python Tutorial
AdaBoost in Python - Machine Learning From Scratch 13 - Python Tutorial
Patrick Loeber
60 Ultimate FREE Study Guide for Machine Learning and Deep Learning
Ultimate FREE Study Guide for Machine Learning and Deep Learning
Patrick Loeber

The Black tool automatically formats Python code, saving time and energy, and can be integrated with version control systems for automated formatting.

Key Takeaways
  1. Install Black using pip
  2. Run Black on a Python file or directory
  3. Configure Black for custom line length using --line-length option
  4. Integrate Black with Git using pre-commit hooks
  5. Use Black as a GitHub Action for automated formatting
💡 Black can save time and energy by automatically formatting Python code, and its integration with version control systems can ensure consistent formatting across a project.

Related AI Lessons

Chapters (4)

Introduction
0:44 Black Overview
2:38 Black Example
5:25 Version Control Integration
Up next
I Asked ChatGPT to Apply to 500 Jobs (8 Interviews in 48 Hours)
Sabrina Ramonov 🍄
Watch →