0Pricing
MCP Academy · Aula

Restrições, padrões e enumerações

Limite valores e ofereça escolhas fixas com segurança.

Restrições, padrões e enumerações é uma aula grátis de MCP Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de MCP Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de MCP Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Beyond Just Types

Types say what kind of value is allowed, but you often want tighter rules: a limit must be positive, a name not empty. That's where constraints come in.

Meet Field

Pydantic's Field lets you attach rules to a field, like minimum and maximum values, right in the model definition.

from pydantic import BaseModel, Field

class Page(BaseModel):
    size: int = Field(ge=1, le=100)

Numeric Bounds

Use ge and le for greater-or-equal and less-or-equal, or gt and lt for strict bounds, to keep numbers in a safe range.

String Length Limits

For text, min_length and max_length stop empty strings and runaway input before they reach your logic.

name: str = Field(min_length=1, max_length=50)

Pattern Matching

Add a pattern to require a string match a regular expression, perfect for codes, slugs, or simple identifiers.

Simple Defaults

Give a field a value and it becomes optional with a default. The model may omit it and your tool uses the fallback.

limit: int = 10

Defaults Inside Field

You can combine a default with constraints by passing it to Field, keeping the rule and the fallback in one place.

limit: int = Field(default=10, ge=1, le=100)

Fixed Choices with Enum

When only a few values make sense, an Enum limits the field to that exact set, so the model cannot invent options.

from enum import Enum

class Sort(str, Enum):
    asc = "asc"
    desc = "desc"

Use the Enum as a Type

Declare a field with the enum type and Pydantic accepts only its members, rejecting any other value automatically.

order: Sort = Sort.asc

Literals for Tiny Sets

For a quick fixed set you can also use Literal, which lists allowed values inline without a separate Enum class.

from typing import Literal
unit: Literal["c", "f"] = "c"

Constraints Reach the Model

These rules become part of the JSON schema, so the model sees the allowed ranges and choices and tends to obey them.

Quick Check

You want a field to accept only asc or desc. What fits best?

Recap

Use Field for bounds and lengths, plain defaults for optional values, and Enum or Literal for fixed choices the model must respect. ✅

Perguntas Frequentes

A aula “Restrições, padrões e enumerações” é grátis?

Sim — o texto completo de “Restrições, padrões e enumerações” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de MCP Academy, atualize para CoddyKit PRO. O curso de MCP Academy inclui 4 aulas no total.

O que vou aprender em “Restrições, padrões e enumerações”?

Limite valores e ofereça escolhas fixas com segurança. Você pratica MCP Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar MCP Academy?

Nenhuma experiência prévia é necessária. MCP Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “Restrições, padrões e enumerações”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de MCP Academy?

Sim. Cada aula de MCP Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Por que os esquemas são melhores que argumentos soltos
  2. Entradas do modelo com Pydantic
  3. Restrições, padrões e enumerações
  4. Descrições de campos que orientam o modelo
← Voltar para MCP Academy