How to use the pydantic.Extra function in pydantic

To help you get started, we’ve selected a few pydantic examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github samuelcolvin / pydantic / tests / test_create_model.py View on Github external
def test_custom_config_extras():
    class Config(BaseModel.Config):
        extra = Extra.forbid

    model = create_model('FooModel', foo=(int, ...), __config__=Config)
    assert model(foo=654)
    with pytest.raises(ValidationError):
        model(bar=654)
github samuelcolvin / pydantic / tests / test_main.py View on Github external
def test_not_immutability():
    class TestModel(BaseModel):
        a: int = 10

        class Config:
            allow_mutation = True
            extra = Extra.forbid

    m = TestModel()
    assert m.a == 10
    m.a = 11
    assert m.a == 11
    with pytest.raises(ValueError) as exc_info:
        m.b = 11
    assert '"TestModel" object has no field "b"' in exc_info.value.args[0]
github samuelcolvin / pydantic / tests / test_main.py View on Github external
def test_forbidden_extra_success():
    class ForbiddenExtra(BaseModel):
        foo = 'whatever'

        class Config:
            extra = Extra.forbid

    m = ForbiddenExtra()
    assert m.foo == 'whatever'

    m = ForbiddenExtra(foo=1)
    assert m.foo == '1'
github samuelcolvin / pydantic / tests / test_main.py View on Github external
def test_allow_extra():
    class Model(BaseModel):
        a: float = ...

        class Config:
            extra = Extra.allow

    assert Model(a='10.2', b=12).dict() == {'a': 10.2, 'b': 12}
github sullivancolin / hexpy / src / hexpy / project.py View on Github external
resultsEnd: pendulum.DateTime
    keywords: str
    languages: JSONDict
    geolocations: JSONDict
    gender: Optional[GenderEnum] = None
    sources: List[str]
    timezone: str
    teamName: str
    tags: List[str]
    subfilters: List[JSONDict]
    categories: List[JSONDict]
    emotions: List[JSONDict]
    session: HexpySession

    class Config:
        extra = Extra.allow
        arbitrary_types_allowed = True

    @validator("gender", pre=True)
    def validate_empty_gender(cls, value: Optional[str]) -> Union[str, None]:
        """Validate empty string is None"""
        if value:
            return value
        else:
            return None

    @classmethod
    def get_from_monitor_id(cls, session: HexpySession, monitor_id: int) -> "Project":
        """Instantiate from session and Monitor ID"""
        client = MonitorAPI(session)
        details = client.details(monitor_id)
        details["session"] = session
github Skyscanner / cfripper / cfripper / model / result.py View on Github external
from pydantic import BaseModel, Extra

from cfripper.model.enums import RuleMode


class Failure(BaseModel):
    granularity: str
    reason: str
    risk_value: str
    rule: str
    rule_mode: str
    actions: Optional[set] = set()
    resource_ids: Optional[set] = set()

    class Config(BaseModel.Config):
        extra = Extra.forbid

    def serializable(self):
        return {
            "rule": self.rule,
            "reason": self.reason,
            "rule_mode": self.rule_mode,
            "risk_value": self.risk_value,
            "resource_ids": sorted(self.resource_ids or []),
            "actions": sorted(self.actions or []),
            "granularity": self.granularity,
        }


class Result(BaseModel):
    class Config(BaseModel.Config):
        extra = Extra.forbid
github layday / instawow / instawow / wa_updater.py View on Github external
id: str
    name: str  # +
    slug: str  # +
    url: str
    created: str
    modified: str
    game: str
    fork_of: O[str]
    username: str  # +
    version: int  # +
    version_string: str  # +
    changelog: _WagoChangelog  # +
    region_type: O[str]

    class Config:
        extra = Extra.forbid
        fields = {
            'id': '_id',
            'fork_of': 'forkOf',
            'version_string': 'versionString',
            'region_type': 'regionType',
        }


class WaCompanionBuilder(ManagerAttrAccessMixin):
    """A WeakAuras Companion port for shellfolk."""

    def __init__(self, manager: Manager, builder_config: BuilderConfig) -> None:
        self.manager = manager
        self.addon_file = self.config.plugin_dir / __name__ / 'WeakAurasCompanion.zip'
        self.builder_config = builder_config
github aiogram / aiogram / aiogram / api / types / base.py View on Github external
from pydantic import BaseConfig, BaseModel, Extra

from aiogram.utils.mixins import ContextInstanceMixin


class TelegramObject(ContextInstanceMixin, BaseModel):
    class Config(BaseConfig):
        use_enum_values = True
        orm_mode = True
        extra = Extra.allow
        allow_mutation = False
        allow_population_by_field_name = True
github uburuntu / rawg / rawg / types.py View on Github external
from datetime import date
from typing import Any, List, Optional

from pydantic import BaseModel, Extra
from pydantic.color import Color


class RawgBase(BaseModel):
    class Config:
        arbitrary_types_allowed = True
        extra = Extra.allow
        validate_all = True
        validate_assignment = True
        use_enum_values = True


class RawgPlatformDataBase(RawgBase):
    id: int
    name: str
    slug: str


class RawgPlatformData(RawgPlatformDataBase):
    games_count: int

    # Optional fields
    image: Optional[str]
github layday / instawow / instawow / config.py View on Github external
def _build_values(self, init_kwargs: Dict[str, Any], _env_file: Any = None) -> Dict[str, Any]:
        # Prioritise env vars
        return {**init_kwargs, **self._build_environ(_env_file)}


class GlobalConfig(BaseConfig):
    config_dir: Path = Field(default_factory=_get_default_config_dir)
    addon_dir: Path
    temp_dir: Path = Path(gettempdir()) / 'instawow'
    game_flavour: Literal['retail', 'classic']
    auto_update_check: bool = True
    profile: O[str] = None

    class Config:
        env_prefix = 'INSTAWOW_'
        extra = Extra.allow

    @validator('config_dir', 'addon_dir', 'temp_dir')
    def _expand_paths(cls, value: Path) -> Path:
        try:
            return value.expanduser().resolve()
        except RuntimeError as error:
            # pathlib will raise RuntimeError for non-existent ~users
            raise ValueError(str(error)) from error

    @validator('addon_dir')
    def _check_writable(cls, value: Path) -> Path:
        if not (value.is_dir() and os.access(value, os.W_OK)):
            raise ValueError('must be a writable directory')
        return value

    @validator('profile')