🖌️ Code style
Code style is important because it makes your code more readable and maintainable. Most projects you work on will be with others and having a consistent and clean code style will make it easier for everyone to understand the codebase.
In this class, you will be partially graded on your code style and formatting. Thankfully, we have tools that can help us with this!
🛠️ Linting and formatting
In this class, we will be using 3 tools to help with code style:
- black - a very opinionated code formatter
- isort - sorts your imports!
- flake8 - a linter for Python code
Most of the time, the initial set up for the tools will be done for you, and just by installing the initial dependencies, you just have to run these formatters before you submit. With VSCode, it's also fairly easy to set up automatic formatting on save which will make life a lot easier!
Command to run the linting and formatting:
black . && isort . && flake8
✏️ Some Syntax Guidelines
- Omit boolean literal comparisons
# ❌ incorrect
if b == True:
...
# ✅ correct
if b:
...
- Use ternary expression instead of
if/else
if possible (unless it becomes super hard to read!)
# ❌ incorrect
if b:
a = 3
else:
a = 2
# ✅ correct
a = 3 if b else 2
- Use lambda functions if you are passing a simple function to another function
# ❌ incorrect
def add_5(x):
return x + 5
result = map(add_5, [1, 2, 3])
# ✅ correct
result = map(lambda x: x + 5, [1, 2, 3])
- Use f-strings instead of string concatenation
s1 = "Jordan"
s2 = "Hochman"
# ❌ incorrect
s = s1 + " " + s2 + " is " + str(50) + " years old"
# ✅ correct
s = f"{s1} {s2} is {50} years old"
- Feel free to use print statements for debugging, but it's often best practice to leave them out of the final code!
It's completely okay to have your own opinions on code style, but for this class, please try to keep to the guidelines. Even more importantly, make sure you are consistent!