Python - use real objects over primitive types
Python Clean Code Tip:
Favor real objects over primitive types such as dictionaries.
Why?
- It's easier to type
user.name
rather thanuser['name']
- You'll get help from your IDE
- You can actually check your code before it runs with mypy
- It makes your code more clear
# bad user = {"first_name": "John", "last_name": "Doe"} full_name = f"{user['first_name']} {user['last_name']}" print(full_name) # => John Doe # better class User: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name def full_name(self): return f"{self.first_name} {self.last_name}" user = User(first_name="John", last_name="Doe") print(user.full_name()) # => John Doe