TECHNOLOGIESTieInn Technologies

Type hints, dataclasses and classes for AI code

Python for AI Apps · 10 questions

Short notes

Key idea

AI code passes around messages, configs and results. Type hints say what each value should be; dataclasses and classes bundle related data and behaviour, so code is easier to read and editors catch mistakes early.

Syntax

from dataclasses import dataclass, field

def score(text: str, keywords: list[str]) -> float: ...

@dataclass
class Message:
    role: str
    text: str
    tokens: int = 0

class Chat:
    def __init__(self, model: str) -> None:
        self.model = model
        self.history: list[Message] = []
    def add(self, m: Message) -> None:
        self.history.append(m)
  • str | None for optional values; dict[str, int] for typed dicts.

Example

Message("user", "Hi") prints as Message(role='user', text='Hi', tokens=0), compares by value, and needs no hand-written __init__.

Traps

  • Type hints aren't enforced at runtime; use Pydantic when input comes from outside.
  • Mutable defaults in dataclasses need field(default_factory=list).
  • Forgetting self in methods is the most common class error.
  • Don't build class hierarchies you don't need; a function or dataclass is often enough.

Want the full lesson with step-by-step examples, a project and a certificate? Python for AI Apps course, ₹180 →

Questions

Open in Code Lab5 free questions
5 questions

    Type hints, dataclasses and classes for AI code

  1. Question 1easy

    What does def top_k(scores: dict[str, float], k: int = 3) -> list[str]: promise?

  2. Type hints, dataclasses and classes for AI code

  3. Question 2medium

    What does this print?

    def greet(name: str | None = None) -> str:
        return f"Hi {name}!" if name else "Hi there!"
    print(greet(), "/", greet("Asha"))
  4. Type hints, dataclasses and classes for AI code

  5. Question 3medium

    What does this print?

    from dataclasses import dataclass, field
    
    @dataclass
    class Doc:
        title: str
        tags: list[str] = field(default_factory=list)
    
    a, b = Doc("Returns"), Doc("Refunds")
    a.tags.append("policy")
    print(len(a.tags), len(b.tags))
  6. Type hints, dataclasses and classes for AI code

  7. Question 4easy

    What does this print?

    from dataclasses import dataclass
    
    @dataclass
    class Message:
        role: str
        content: str
    
    print(Message("user", "Hi") == Message("user", "Hi"))
  8. Type hints, dataclasses and classes for AI code

  9. Question 5medium

    What does this print?

    class Bot:
        def __init__(self):
            self.history = []
        def say(self, text):
            self.history.append(text)
            return len(self.history)
    
    asha, ravi = Bot(), Bot()
    asha.say("hi")
    asha.say("order 5?")
    print(ravi.say("hello"))

5 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.