Python - use real objects over primitive types


Python Clean Code Tip:

Favor real objects over primitive types such as dictionaries.

Why?

  1. It's easier to type user.name rather than user['name']
  2. You'll get help from your IDE
  3. You can actually check your code before it runs with mypy
  4. 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