From ec1dca912645852bf5d25b91b664083a7c5e5d62 Mon Sep 17 00:00:00 2001 From: Stephen Brown II Date: Sun, 31 May 2020 07:54:12 -0600 Subject: [PATCH] Add linting for docs/examples (#1530) --- Makefile | 1 + docs/build/exec_examples.py | 2 +- docs/examples/dataclasses_default_schema.py | 2 ++ docs/examples/dataclasses_initvars.py | 2 ++ docs/examples/dataclasses_json_dumps.py | 2 ++ docs/examples/dataclasses_main.py | 2 ++ docs/examples/dataclasses_nested.py | 3 +++ .../dataclasses_post_init_post_parse.py | 4 +++- docs/examples/devtools_main.py | 5 ++++- docs/examples/exporting_models_copy.py | 3 +++ docs/examples/exporting_models_dict.py | 3 +++ docs/examples/exporting_models_exclude1.py | 5 ++++- docs/examples/exporting_models_exclude2.py | 13 +++++++++---- docs/examples/exporting_models_iterate.py | 4 +++- docs/examples/exporting_models_json.py | 3 +++ .../exporting_models_json_encoders.py | 2 ++ .../exporting_models_json_subclass.py | 4 ++++ docs/examples/exporting_models_orjson.py | 3 +++ docs/examples/exporting_models_pickle.py | 2 ++ docs/examples/exporting_models_ujson.py | 2 ++ docs/examples/index_error.py | 1 + docs/examples/index_main.py | 4 +++- docs/examples/model_config_alias_generator.py | 3 +++ .../examples/model_config_alias_precedence.py | 3 +++ docs/examples/model_config_dataclass.py | 3 +++ docs/examples/model_config_main.py | 2 ++ docs/examples/models_abc.py | 1 + docs/examples/models_construct.py | 2 ++ docs/examples/models_custom_root_access.py | 6 ++++-- docs/examples/models_custom_root_field.py | 2 ++ .../models_custom_root_field_parse_obj.py | 4 ++++ docs/examples/models_data_conversion.py | 2 ++ docs/examples/models_default_factory.py | 2 ++ docs/examples/models_dynamic_creation.py | 1 + docs/examples/models_dynamic_inheritance.py | 2 ++ docs/examples/models_errors1.py | 3 +++ docs/examples/models_errors2.py | 3 ++- docs/examples/models_errors3.py | 3 +++ docs/examples/models_field_order.py | 2 ++ docs/examples/models_generics.py | 4 ++++ docs/examples/models_generics_inheritance.py | 3 +++ docs/examples/models_generics_naming.py | 2 ++ docs/examples/models_generics_nested.py | 3 +++ docs/examples/models_generics_typevars.py | 2 ++ docs/examples/models_mutation.py | 2 ++ docs/examples/models_orm_mode.py | 5 ++++- docs/examples/models_orm_mode_recursive.py | 5 +++++ docs/examples/models_parse.py | 7 +++++-- docs/examples/models_recursive.py | 4 ++++ .../models_required_field_optional.py | 2 ++ docs/examples/models_required_fields.py | 1 + docs/examples/models_signature.py | 2 ++ docs/examples/models_signature_custom_init.py | 2 ++ docs/examples/mypy_main.py | 2 ++ docs/examples/parse_obj_as.py | 2 ++ docs/examples/postponed_annotations_broken.py | 3 +++ .../postponed_annotations_forward_ref.py | 2 ++ docs/examples/postponed_annotations_main.py | 2 ++ ...nnotations_self_referencing_annotations.py | 2 ++ ...ned_annotations_self_referencing_string.py | 2 ++ docs/examples/postponed_annotations_works.py | 2 ++ docs/examples/schema_custom.py | 4 +++- docs/examples/schema_extra_callable.py | 2 ++ docs/examples/schema_main.py | 5 +++++ docs/examples/schema_top_level.py | 5 ++++- .../examples/schema_unenforced_constraints.py | 4 ++++ docs/examples/schema_with_example.py | 2 ++ docs/examples/settings_case_sensitive.py | 1 + docs/examples/settings_main.py | 10 +++++++++- docs/examples/types_arbitrary_allowed.py | 3 +++ docs/examples/types_bare_type.py | 3 +++ docs/examples/types_boolean.py | 2 ++ docs/examples/types_bytesize.py | 2 ++ docs/examples/types_callable.py | 2 ++ docs/examples/types_choices.py | 4 ++++ docs/examples/types_color.py | 3 +++ docs/examples/types_constrained.py | 3 ++- docs/examples/types_custom_type.py | 4 ++++ docs/examples/types_dt.py | 4 +++- docs/examples/types_generics.py | 7 +++++-- docs/examples/types_infinite_generator.py | 3 +++ ...types_infinite_generator_validate_first.py | 5 +++++ docs/examples/types_iterables.py | 2 ++ docs/examples/types_json_type.py | 3 +++ docs/examples/types_literal1.py | 2 ++ docs/examples/types_literal2.py | 4 ++++ docs/examples/types_literal3.py | 6 ++++++ docs/examples/types_payment_card_number.py | 4 +++- docs/examples/types_secret_types.py | 9 +++++++-- docs/examples/types_strict.py | 10 +++++++--- docs/examples/types_type.py | 5 +++++ docs/examples/types_typevar.py | 2 ++ docs/examples/types_union_correct.py | 2 ++ docs/examples/types_union_incorrect.py | 2 ++ docs/examples/types_url_properties.py | 6 +++++- docs/examples/types_url_punycode.py | 2 ++ docs/examples/types_urls.py | 2 ++ docs/examples/validation_decorator_async.py | 4 ++++ docs/examples/validation_decorator_main.py | 2 ++ .../validation_decorator_parameter_types.py | 14 +++++++++++++- .../validation_decorator_raw_function.py | 2 ++ docs/examples/validation_decorator_types.py | 2 ++ docs/examples/validators_allow_reuse.py | 4 ++++ docs/examples/validators_always.py | 2 ++ docs/examples/validators_dataclass.py | 2 ++ docs/examples/validators_pre_item.py | 5 +++-- docs/examples/validators_root.py | 10 ++++++++-- docs/examples/validators_simple.py | 19 +++++++++++++++---- setup.cfg | 4 ++++ 109 files changed, 347 insertions(+), 39 deletions(-) diff --git a/Makefile b/Makefile index 715ddd7..3931367 100644 --- a/Makefile +++ b/Makefile @@ -107,6 +107,7 @@ clean: .PHONY: docs docs: + flake8 --max-line-length=80 docs/examples/ python docs/build/main.py mkdocs build diff --git a/docs/build/exec_examples.py b/docs/build/exec_examples.py index 469bb3e..2f167f5 100755 --- a/docs/build/exec_examples.py +++ b/docs/build/exec_examples.py @@ -155,7 +155,7 @@ def exec_examples(): error('file not used anywhere') file_text = file.read_text('utf-8') - if '\n\n\n' in file_text: + if '\n\n\n\n' in file_text: error('too many new lines') if not file_text.endswith('\n'): error('no trailing new line') diff --git a/docs/examples/dataclasses_default_schema.py b/docs/examples/dataclasses_default_schema.py index 58d8b3e..125b5e7 100644 --- a/docs/examples/dataclasses_default_schema.py +++ b/docs/examples/dataclasses_default_schema.py @@ -2,11 +2,13 @@ import dataclasses from typing import List from pydantic.dataclasses import dataclass + @dataclass class User: id: int name: str = 'John Doe' friends: List[int] = dataclasses.field(default_factory=lambda: [0]) + user = User(id='42') print(user.__pydantic_model__.schema()) diff --git a/docs/examples/dataclasses_initvars.py b/docs/examples/dataclasses_initvars.py index cc5a05b..ead7149 100644 --- a/docs/examples/dataclasses_initvars.py +++ b/docs/examples/dataclasses_initvars.py @@ -4,6 +4,7 @@ from typing import Optional from pydantic.dataclasses import dataclass + @dataclass class PathData: path: Path @@ -16,6 +17,7 @@ class PathData: if base_path is not None: self.path = base_path / self.path + path_data = PathData('world', base_path='/hello') # Received path='world', base_path='/hello' assert path_data.path == Path('/hello/world') diff --git a/docs/examples/dataclasses_json_dumps.py b/docs/examples/dataclasses_json_dumps.py index 91179a3..80266b9 100644 --- a/docs/examples/dataclasses_json_dumps.py +++ b/docs/examples/dataclasses_json_dumps.py @@ -5,11 +5,13 @@ from typing import List from pydantic.dataclasses import dataclass from pydantic.json import pydantic_encoder + @dataclass class User: id: int name: str = 'John Doe' friends: List[int] = dataclasses.field(default_factory=lambda: [0]) + user = User(id='42') print(json.dumps(user, indent=4, default=pydantic_encoder)) diff --git a/docs/examples/dataclasses_main.py b/docs/examples/dataclasses_main.py index 16e4178..415bb4f 100644 --- a/docs/examples/dataclasses_main.py +++ b/docs/examples/dataclasses_main.py @@ -1,11 +1,13 @@ from datetime import datetime from pydantic.dataclasses import dataclass + @dataclass class User: id: int name: str = 'John Doe' signup_ts: datetime = None + user = User(id='42', signup_ts='2032-06-21T12:00') print(user) diff --git a/docs/examples/dataclasses_nested.py b/docs/examples/dataclasses_nested.py index 08cc7fb..f3e73c3 100644 --- a/docs/examples/dataclasses_nested.py +++ b/docs/examples/dataclasses_nested.py @@ -1,13 +1,16 @@ from pydantic import AnyUrl from pydantic.dataclasses import dataclass + @dataclass class NavbarButton: href: AnyUrl + @dataclass class Navbar: button: NavbarButton + navbar = Navbar(button=('https://example.com',)) print(navbar) diff --git a/docs/examples/dataclasses_post_init_post_parse.py b/docs/examples/dataclasses_post_init_post_parse.py index 40ff3e3..b5ae4fd 100644 --- a/docs/examples/dataclasses_post_init_post_parse.py +++ b/docs/examples/dataclasses_post_init_post_parse.py @@ -1,12 +1,13 @@ -from datetime import datetime from pydantic.dataclasses import dataclass + @dataclass class Birth: year: int month: int day: int + @dataclass class User: birth: Birth @@ -17,4 +18,5 @@ class User: def __post_init_post_parse__(self): print(self.birth) + user = User(**{'birth': {'year': 1995, 'month': 3, 'day': 2}}) diff --git a/docs/examples/devtools_main.py b/docs/examples/devtools_main.py index b4fdbf4..f0d7e6b 100644 --- a/docs/examples/devtools_main.py +++ b/docs/examples/devtools_main.py @@ -5,12 +5,14 @@ from pydantic import BaseModel from devtools import debug + class Address(BaseModel): street: str country: str lat: float lng: float + class User(BaseModel): id: int name: str @@ -18,12 +20,13 @@ class User(BaseModel): friends: List[int] address: Address + user = User( id='123', name='John Doe', signup_ts='2019-06-01 12:22', friends=[1234, 4567, 7890], - address=dict(street='Testing', country='uk', lat=51.5, lng=0) + address=dict(street='Testing', country='uk', lat=51.5, lng=0), ) debug(user) print('\nshould be much easier read than:\n') diff --git a/docs/examples/exporting_models_copy.py b/docs/examples/exporting_models_copy.py index b0bedee..d6d6814 100644 --- a/docs/examples/exporting_models_copy.py +++ b/docs/examples/exporting_models_copy.py @@ -1,13 +1,16 @@ from pydantic import BaseModel + class BarModel(BaseModel): whatever: int + class FooBarModel(BaseModel): banana: float foo: str bar: BarModel + m = FooBarModel(banana=3.14, foo='hello', bar={'whatever': 123}) print(m.copy(include={'foo', 'bar'})) diff --git a/docs/examples/exporting_models_dict.py b/docs/examples/exporting_models_dict.py index 5caa318..9e6bec4 100644 --- a/docs/examples/exporting_models_dict.py +++ b/docs/examples/exporting_models_dict.py @@ -1,13 +1,16 @@ from pydantic import BaseModel + class BarModel(BaseModel): whatever: int + class FooBarModel(BaseModel): banana: float foo: str bar: BarModel + m = FooBarModel(banana=3.14, foo='hello', bar={'whatever': 123}) # returns a dictionary: diff --git a/docs/examples/exporting_models_exclude1.py b/docs/examples/exporting_models_exclude1.py index 02fb3ae..386c1cf 100644 --- a/docs/examples/exporting_models_exclude1.py +++ b/docs/examples/exporting_models_exclude1.py @@ -1,15 +1,18 @@ from pydantic import BaseModel, SecretStr + class User(BaseModel): id: int username: str password: SecretStr + class Transaction(BaseModel): id: str user: User value: int + t = Transaction( id='1234567890', user=User( @@ -17,7 +20,7 @@ t = Transaction( username='JohnDoe', password='hashedpassword' ), - value=9876543210 + value=9876543210, ) # using a set: diff --git a/docs/examples/exporting_models_exclude2.py b/docs/examples/exporting_models_exclude2.py index 60c62c9..9c5ce06 100644 --- a/docs/examples/exporting_models_exclude2.py +++ b/docs/examples/exporting_models_exclude2.py @@ -3,22 +3,27 @@ from typing import List from pydantic import BaseModel, SecretStr + class Country(BaseModel): name: str phone_code: int + class Address(BaseModel): post_code: int country: Country + class CardDetails(BaseModel): number: SecretStr expires: datetime.date + class Hobby(BaseModel): name: str info: str + class User(BaseModel): first_name: str second_name: str @@ -26,6 +31,7 @@ class User(BaseModel): card_details: CardDetails hobbies: List[Hobby] + user = User( first_name='John', second_name='Doe', @@ -42,9 +48,8 @@ user = User( ), hobbies=[ Hobby(name='Programming', info='Writing code and stuff'), - Hobby(name='Gaming', info='Hell Yeah!!!') - ] - + Hobby(name='Gaming', info='Hell Yeah!!!'), + ], ) exclude_keys = { @@ -58,7 +63,7 @@ exclude_keys = { include_keys = { 'first_name': ..., 'address': {'country': {'name'}}, - 'hobbies': {0: ..., -1: {'name'}} + 'hobbies': {0: ..., -1: {'name'}}, } # would be the same as user.dict(exclude=exclude_keys) in this case: diff --git a/docs/examples/exporting_models_iterate.py b/docs/examples/exporting_models_iterate.py index 12ec3fd..6236a9b 100644 --- a/docs/examples/exporting_models_iterate.py +++ b/docs/examples/exporting_models_iterate.py @@ -1,16 +1,18 @@ from pydantic import BaseModel + class BarModel(BaseModel): whatever: int + class FooBarModel(BaseModel): banana: float foo: str bar: BarModel + m = FooBarModel(banana=3.14, foo='hello', bar={'whatever': 123}) print(dict(m)) for name, value in m: print(f'{name}: {value}') - diff --git a/docs/examples/exporting_models_json.py b/docs/examples/exporting_models_json.py index 86e7c65..062b106 100644 --- a/docs/examples/exporting_models_json.py +++ b/docs/examples/exporting_models_json.py @@ -1,12 +1,15 @@ from datetime import datetime from pydantic import BaseModel + class BarModel(BaseModel): whatever: int + class FooBarModel(BaseModel): foo: datetime bar: BarModel + m = FooBarModel(foo=datetime(2032, 6, 1, 12, 13, 14), bar={'whatever': 123}) print(m.json()) diff --git a/docs/examples/exporting_models_json_encoders.py b/docs/examples/exporting_models_json_encoders.py index 46d8c60..fa70950 100644 --- a/docs/examples/exporting_models_json_encoders.py +++ b/docs/examples/exporting_models_json_encoders.py @@ -2,6 +2,7 @@ from datetime import datetime, timedelta from pydantic import BaseModel from pydantic.json import timedelta_isoformat + class WithCustomEncoders(BaseModel): dt: datetime diff: timedelta @@ -12,5 +13,6 @@ class WithCustomEncoders(BaseModel): timedelta: timedelta_isoformat, } + m = WithCustomEncoders(dt=datetime(2032, 6, 1), diff=timedelta(hours=100)) print(m.json()) diff --git a/docs/examples/exporting_models_json_subclass.py b/docs/examples/exporting_models_json_subclass.py index 8dc266e..43c0a24 100644 --- a/docs/examples/exporting_models_json_subclass.py +++ b/docs/examples/exporting_models_json_subclass.py @@ -2,11 +2,13 @@ from datetime import date, timedelta from pydantic import BaseModel from pydantic.validators import int_validator + class DayThisYear(date): """ Contrived example of a special type of date that takes an int and interprets it as a day in the current year """ + @classmethod def __get_validators__(cls): yield int_validator @@ -16,8 +18,10 @@ class DayThisYear(date): def validate(cls, v: int): return date.today().replace(month=1, day=1) + timedelta(days=v) + class FooModel(BaseModel): date: DayThisYear + m = FooModel(date=300) print(m.json()) diff --git a/docs/examples/exporting_models_orjson.py b/docs/examples/exporting_models_orjson.py index 173f5ed..3b3d726 100644 --- a/docs/examples/exporting_models_orjson.py +++ b/docs/examples/exporting_models_orjson.py @@ -2,10 +2,12 @@ from datetime import datetime import orjson from pydantic import BaseModel + def orjson_dumps(v, *, default): # orjson.dumps returns bytes, to match standard json.dumps we need to decode return orjson.dumps(v, default=default).decode() + class User(BaseModel): id: int name = 'John Doe' @@ -15,5 +17,6 @@ class User(BaseModel): json_loads = orjson.loads json_dumps = orjson_dumps + user = User.parse_raw('{"id":123,"signup_ts":1234567890,"name":"John Doe"}') print(user.json()) diff --git a/docs/examples/exporting_models_pickle.py b/docs/examples/exporting_models_pickle.py index 1020cfa..72d4c63 100644 --- a/docs/examples/exporting_models_pickle.py +++ b/docs/examples/exporting_models_pickle.py @@ -1,10 +1,12 @@ import pickle from pydantic import BaseModel + class FooBarModel(BaseModel): a: str b: int + m = FooBarModel(a='hello', b=123) print(m) data = pickle.dumps(m) diff --git a/docs/examples/exporting_models_ujson.py b/docs/examples/exporting_models_ujson.py index bfaa35d..547295b 100644 --- a/docs/examples/exporting_models_ujson.py +++ b/docs/examples/exporting_models_ujson.py @@ -2,6 +2,7 @@ from datetime import datetime import ujson from pydantic import BaseModel + class User(BaseModel): id: int name = 'John Doe' @@ -10,5 +11,6 @@ class User(BaseModel): class Config: json_loads = ujson.loads + user = User.parse_raw('{"id": 123,"signup_ts":1234567890,"name":"John Doe"}') print(user) diff --git a/docs/examples/index_error.py b/docs/examples/index_error.py index ffecf2e..7f49530 100644 --- a/docs/examples/index_error.py +++ b/docs/examples/index_error.py @@ -1,5 +1,6 @@ # output-json from index_main import User + # ignore-above from pydantic import ValidationError diff --git a/docs/examples/index_main.py b/docs/examples/index_main.py index 99576da..73727cb 100644 --- a/docs/examples/index_main.py +++ b/docs/examples/index_main.py @@ -2,16 +2,18 @@ from datetime import datetime from typing import List, Optional from pydantic import BaseModel + class User(BaseModel): id: int name = 'John Doe' signup_ts: Optional[datetime] = None friends: List[int] = [] + external_data = { 'id': '123', 'signup_ts': '2019-06-01 12:22', - 'friends': [1, 2, '3'] + 'friends': [1, 2, '3'], } user = User(**external_data) print(user.id) diff --git a/docs/examples/model_config_alias_generator.py b/docs/examples/model_config_alias_generator.py index d957bba..b5b9b47 100644 --- a/docs/examples/model_config_alias_generator.py +++ b/docs/examples/model_config_alias_generator.py @@ -1,8 +1,10 @@ from pydantic import BaseModel + def to_camel(string: str) -> str: return ''.join(word.capitalize() for word in string.split('_')) + class Voice(BaseModel): name: str language_code: str @@ -10,6 +12,7 @@ class Voice(BaseModel): class Config: alias_generator = to_camel + voice = Voice(Name='Filiz', LanguageCode='tr-TR') print(voice.language_code) print(voice.dict(by_alias=True)) diff --git a/docs/examples/model_config_alias_precedence.py b/docs/examples/model_config_alias_precedence.py index 3babb24..5953b3b 100644 --- a/docs/examples/model_config_alias_precedence.py +++ b/docs/examples/model_config_alias_precedence.py @@ -1,10 +1,12 @@ from pydantic import BaseModel, Field + class Voice(BaseModel): name: str = Field(None, alias='ActorName') language_code: str = None mood: str = None + class Character(Voice): act: int = 1 @@ -16,4 +18,5 @@ class Character(Voice): # this is the same as `alias_generator = to_camel` above return ''.join(word.capitalize() for word in string.split('_')) + print(Character.schema(by_alias=True)) diff --git a/docs/examples/model_config_dataclass.py b/docs/examples/model_config_dataclass.py index 92fdb0b..ada969d 100644 --- a/docs/examples/model_config_dataclass.py +++ b/docs/examples/model_config_dataclass.py @@ -3,6 +3,7 @@ from datetime import datetime from pydantic import ValidationError from pydantic.dataclasses import dataclass + class MyConfig: max_anystr_length = 10 validate_assignment = True @@ -10,12 +11,14 @@ class MyConfig: 'value_error.any_str.max_length': 'max_length:{limit_value}', } + @dataclass(config=MyConfig) class User: id: int name: str = 'John Doe' signup_ts: datetime = None + user = User(id='42', signup_ts='2032-06-21T12:00') try: user.name = 'x' * 20 diff --git a/docs/examples/model_config_main.py b/docs/examples/model_config_main.py index f6022ac..25e2df4 100644 --- a/docs/examples/model_config_main.py +++ b/docs/examples/model_config_main.py @@ -1,5 +1,6 @@ from pydantic import BaseModel, ValidationError + class Model(BaseModel): v: str @@ -9,6 +10,7 @@ class Model(BaseModel): 'value_error.any_str.max_length': 'max_length:{limit_value}', } + try: Model(v='x' * 20) except ValidationError as e: diff --git a/docs/examples/models_abc.py b/docs/examples/models_abc.py index 3e7c04a..f325199 100644 --- a/docs/examples/models_abc.py +++ b/docs/examples/models_abc.py @@ -1,6 +1,7 @@ import abc from pydantic import BaseModel + class FooBarModel(BaseModel, abc.ABC): a: str b: int diff --git a/docs/examples/models_construct.py b/docs/examples/models_construct.py index 54cbf43..9acf1d8 100644 --- a/docs/examples/models_construct.py +++ b/docs/examples/models_construct.py @@ -1,10 +1,12 @@ from pydantic import BaseModel + class User(BaseModel): id: int age: int name: str = 'John Doe' + original_user = User(id=123, age=32) user_data = original_user.dict() diff --git a/docs/examples/models_custom_root_access.py b/docs/examples/models_custom_root_access.py index 64739e4..152951e 100644 --- a/docs/examples/models_custom_root_access.py +++ b/docs/examples/models_custom_root_access.py @@ -1,5 +1,6 @@ -from typing import List, Dict -from pydantic import BaseModel, ValidationError +from typing import List +from pydantic import BaseModel + class Pets(BaseModel): __root__: List[str] @@ -10,6 +11,7 @@ class Pets(BaseModel): def __getitem__(self, item): return self.__root__[item] + pets = Pets.parse_obj(['dog', 'cat']) print(pets[0]) print([pet for pet in pets]) diff --git a/docs/examples/models_custom_root_field.py b/docs/examples/models_custom_root_field.py index bdf55b7..704ce5c 100644 --- a/docs/examples/models_custom_root_field.py +++ b/docs/examples/models_custom_root_field.py @@ -3,9 +3,11 @@ import json from pydantic import BaseModel from pydantic.schema import schema + class Pets(BaseModel): __root__: List[str] + print(Pets(__root__=['dog', 'cat'])) print(Pets(__root__=['dog', 'cat']).json()) print(Pets.parse_obj(['dog', 'cat'])) diff --git a/docs/examples/models_custom_root_field_parse_obj.py b/docs/examples/models_custom_root_field_parse_obj.py index f5d3da2..d6d9ca4 100644 --- a/docs/examples/models_custom_root_field_parse_obj.py +++ b/docs/examples/models_custom_root_field_parse_obj.py @@ -1,15 +1,19 @@ from typing import List, Dict from pydantic import BaseModel, ValidationError + class Pets(BaseModel): __root__: List[str] + print(Pets.parse_obj(['dog', 'cat'])) print(Pets.parse_obj({'__root__': ['dog', 'cat']})) # not recommended + class PetsByName(BaseModel): __root__: Dict[str, str] + print(PetsByName.parse_obj({'Otis': 'dog', 'Milo': 'cat'})) try: PetsByName.parse_obj({'__root__': {'Otis': 'dog', 'Milo': 'cat'}}) diff --git a/docs/examples/models_data_conversion.py b/docs/examples/models_data_conversion.py index 27f9b66..a8586db 100644 --- a/docs/examples/models_data_conversion.py +++ b/docs/examples/models_data_conversion.py @@ -1,8 +1,10 @@ from pydantic import BaseModel + class Model(BaseModel): a: int b: float c: str + print(Model(a=3.1415, b=' 2.72 ', c=123).dict()) diff --git a/docs/examples/models_default_factory.py b/docs/examples/models_default_factory.py index 7d45e5d..44b247d 100644 --- a/docs/examples/models_default_factory.py +++ b/docs/examples/models_default_factory.py @@ -2,10 +2,12 @@ from datetime import datetime from uuid import UUID, uuid4 from pydantic import BaseModel, Field + class Model(BaseModel): uid: UUID = Field(default_factory=uuid4) updated: datetime = Field(default_factory=datetime.utcnow) + m1 = Model() m2 = Model() print(f'{m1.uid} != {m2.uid}') diff --git a/docs/examples/models_dynamic_creation.py b/docs/examples/models_dynamic_creation.py index 6c9ea30..7e5d5c3 100644 --- a/docs/examples/models_dynamic_creation.py +++ b/docs/examples/models_dynamic_creation.py @@ -2,6 +2,7 @@ from pydantic import BaseModel, create_model DynamicFoobarModel = create_model('DynamicFoobarModel', foo=(str, ...), bar=123) + class StaticFoobarModel(BaseModel): foo: str bar: int = 123 diff --git a/docs/examples/models_dynamic_inheritance.py b/docs/examples/models_dynamic_inheritance.py index 3a99e90..21d75a0 100644 --- a/docs/examples/models_dynamic_inheritance.py +++ b/docs/examples/models_dynamic_inheritance.py @@ -1,9 +1,11 @@ from pydantic import BaseModel, create_model + class FooModel(BaseModel): foo: str bar: int = 123 + BarModel = create_model( 'BarModel', apple='russet', diff --git a/docs/examples/models_errors1.py b/docs/examples/models_errors1.py index 2c30782..ea9ebc9 100644 --- a/docs/examples/models_errors1.py +++ b/docs/examples/models_errors1.py @@ -1,10 +1,12 @@ from typing import List from pydantic import BaseModel, ValidationError, conint + class Location(BaseModel): lat = 0.1 lng = 10.1 + class Model(BaseModel): is_required: float gt_int: conint(gt=42) @@ -12,6 +14,7 @@ class Model(BaseModel): a_float: float = None recursive_model: Location = None + data = dict( list_of_ints=['1', 2, 'bad'], a_float='not a float', diff --git a/docs/examples/models_errors2.py b/docs/examples/models_errors2.py index 88f06d4..28c81e6 100644 --- a/docs/examples/models_errors2.py +++ b/docs/examples/models_errors2.py @@ -1,5 +1,6 @@ from pydantic import BaseModel, ValidationError, validator + class Model(BaseModel): foo: str @@ -10,8 +11,8 @@ class Model(BaseModel): return v + try: Model(foo='ber') except ValidationError as e: print(e.errors()) - diff --git a/docs/examples/models_errors3.py b/docs/examples/models_errors3.py index 4c54bef..36ba646 100644 --- a/docs/examples/models_errors3.py +++ b/docs/examples/models_errors3.py @@ -1,9 +1,11 @@ from pydantic import BaseModel, PydanticValueError, ValidationError, validator + class NotABarError(PydanticValueError): code = 'not_a_bar' msg_template = 'value is not "bar", got "{wrong_value}"' + class Model(BaseModel): foo: str @@ -13,6 +15,7 @@ class Model(BaseModel): raise NotABarError(wrong_value=v) return v + try: Model(foo='ber') except ValidationError as e: diff --git a/docs/examples/models_field_order.py b/docs/examples/models_field_order.py index 238c477..99cfac2 100644 --- a/docs/examples/models_field_order.py +++ b/docs/examples/models_field_order.py @@ -1,5 +1,6 @@ from pydantic import BaseModel, ValidationError + class Model(BaseModel): a: int b = 2 @@ -7,6 +8,7 @@ class Model(BaseModel): d = 0 e: float + print(Model.__fields__.keys()) m = Model(e=2, a=1) print(m.dict()) diff --git a/docs/examples/models_generics.py b/docs/examples/models_generics.py index 6ff2d59..81ce3fc 100644 --- a/docs/examples/models_generics.py +++ b/docs/examples/models_generics.py @@ -5,14 +5,17 @@ from pydantic.generics import GenericModel DataT = TypeVar('DataT') + class Error(BaseModel): code: int message: str + class DataModel(BaseModel): numbers: List[int] people: List[str] + class Response(GenericModel, Generic[DataT]): data: Optional[DataT] error: Optional[Error] @@ -25,6 +28,7 @@ class Response(GenericModel, Generic[DataT]): raise ValueError('must provide data or error') return v + data = DataModel(numbers=[1, 2, 3], people=[]) error = Error(code=404, message='Not found') diff --git a/docs/examples/models_generics_inheritance.py b/docs/examples/models_generics_inheritance.py index 297dbd4..0008b10 100644 --- a/docs/examples/models_generics_inheritance.py +++ b/docs/examples/models_generics_inheritance.py @@ -3,12 +3,15 @@ from pydantic.generics import GenericModel TypeX = TypeVar('TypeX') + class BaseClass(GenericModel, Generic[TypeX]): X: TypeX + class ChildClass(BaseClass[TypeX], Generic[TypeX]): # Inherit from Generic[TypeX] pass + # Replace TypeX by int print(ChildClass[int](X=1)) diff --git a/docs/examples/models_generics_naming.py b/docs/examples/models_generics_naming.py index db72045..e55742b 100644 --- a/docs/examples/models_generics_naming.py +++ b/docs/examples/models_generics_naming.py @@ -4,6 +4,7 @@ from pydantic.generics import GenericModel DataT = TypeVar('DataT') + class Response(GenericModel, Generic[DataT]): data: DataT @@ -11,5 +12,6 @@ class Response(GenericModel, Generic[DataT]): def __concrete_name__(cls: Type[Any], params: Tuple[Type[Any], ...]) -> str: return f'{params[0].__name__.title()}Response' + print(Response[int](data=1)) print(Response[str](data='a')) diff --git a/docs/examples/models_generics_nested.py b/docs/examples/models_generics_nested.py index d590102..0d0e4bc 100644 --- a/docs/examples/models_generics_nested.py +++ b/docs/examples/models_generics_nested.py @@ -5,13 +5,16 @@ from pydantic.generics import GenericModel T = TypeVar('T') + class InnerT(GenericModel, Generic[T]): inner: T + class OuterT(GenericModel, Generic[T]): outer: T nested: InnerT[T] + nested = InnerT[int](inner=1) print(OuterT[int](outer=1, nested=nested)) try: diff --git a/docs/examples/models_generics_typevars.py b/docs/examples/models_generics_typevars.py index ea15619..2cec527 100644 --- a/docs/examples/models_generics_typevars.py +++ b/docs/examples/models_generics_typevars.py @@ -6,10 +6,12 @@ from pydantic.generics import GenericModel AT = TypeVar('AT') BT = TypeVar('BT') + class Model(GenericModel, Generic[AT, BT]): a: AT b: BT + print(Model(a='a', b='a')) IntT = TypeVar('IntT', bound=int) diff --git a/docs/examples/models_mutation.py b/docs/examples/models_mutation.py index 6bcd045..bfc4587 100644 --- a/docs/examples/models_mutation.py +++ b/docs/examples/models_mutation.py @@ -1,5 +1,6 @@ from pydantic import BaseModel + class FooBarModel(BaseModel): a: str b: dict @@ -7,6 +8,7 @@ class FooBarModel(BaseModel): class Config: allow_mutation = False + foobar = FooBarModel(a='hello', b={'apple': 'pear'}) try: diff --git a/docs/examples/models_orm_mode.py b/docs/examples/models_orm_mode.py index 8b76ee0..1bec2ea 100644 --- a/docs/examples/models_orm_mode.py +++ b/docs/examples/models_orm_mode.py @@ -6,6 +6,7 @@ from pydantic import BaseModel, constr Base = declarative_base() + class CompanyOrm(Base): __tablename__ = 'companies' id = Column(Integer, primary_key=True, nullable=False) @@ -13,6 +14,7 @@ class CompanyOrm(Base): name = Column(String(63), unique=True) domains = Column(ARRAY(String(255))) + class CompanyModel(BaseModel): id: int public_key: constr(max_length=20) @@ -22,11 +24,12 @@ class CompanyModel(BaseModel): class Config: orm_mode = True + co_orm = CompanyOrm( id=123, public_key='foobar', name='Testing', - domains=['example.com', 'foobar.com'] + domains=['example.com', 'foobar.com'], ) print(co_orm) co_model = CompanyModel.from_orm(co_orm) diff --git a/docs/examples/models_orm_mode_recursive.py b/docs/examples/models_orm_mode_recursive.py index 47a16eb..edbdd67 100644 --- a/docs/examples/models_orm_mode_recursive.py +++ b/docs/examples/models_orm_mode_recursive.py @@ -1,17 +1,20 @@ from typing import List from pydantic import BaseModel + class PetCls: def __init__(self, *, name: str, species: str): self.name = name self.species = species + class PersonCls: def __init__(self, *, name: str, age: float = None, pets: List[PetCls]): self.name = name self.age = age self.pets = pets + class Pet(BaseModel): name: str species: str @@ -19,6 +22,7 @@ class Pet(BaseModel): class Config: orm_mode = True + class Person(BaseModel): name: str age: float = None @@ -27,6 +31,7 @@ class Person(BaseModel): class Config: orm_mode = True + bones = PetCls(name='Bones', species='dog') orion = PetCls(name='Orion', species='cat') anna = PersonCls(name='Anna', age=20, pets=[bones, orion]) diff --git a/docs/examples/models_parse.py b/docs/examples/models_parse.py index bba72c9..5cdcf55 100644 --- a/docs/examples/models_parse.py +++ b/docs/examples/models_parse.py @@ -2,11 +2,13 @@ import pickle from datetime import datetime from pydantic import BaseModel, ValidationError + class User(BaseModel): id: int name = 'John Doe' signup_ts: datetime = None + m = User.parse_obj({'id': 123, 'name': 'James'}) print(m) @@ -24,6 +26,7 @@ pickle_data = pickle.dumps({ 'name': 'James', 'signup_ts': datetime(2017, 7, 14) }) -m = User.parse_raw(pickle_data, content_type='application/pickle', - allow_pickle=True) +m = User.parse_raw( + pickle_data, content_type='application/pickle', allow_pickle=True +) print(m) diff --git a/docs/examples/models_recursive.py b/docs/examples/models_recursive.py index 117bb00..57c5a92 100644 --- a/docs/examples/models_recursive.py +++ b/docs/examples/models_recursive.py @@ -1,18 +1,22 @@ from typing import List from pydantic import BaseModel + class Foo(BaseModel): count: int size: float = None + class Bar(BaseModel): apple = 'x' banana = 'y' + class Spam(BaseModel): foo: Foo bars: List[Bar] + m = Spam(foo={'count': 4}, bars=[{'apple': 'x1'}, {'apple': 'x2'}]) print(m) print(m.dict()) diff --git a/docs/examples/models_required_field_optional.py b/docs/examples/models_required_field_optional.py index aa018c4..562abf3 100644 --- a/docs/examples/models_required_field_optional.py +++ b/docs/examples/models_required_field_optional.py @@ -1,11 +1,13 @@ from typing import Optional from pydantic import BaseModel, Field, ValidationError + class Model(BaseModel): a: Optional[int] b: Optional[int] = ... c: Optional[int] = Field(...) + print(Model(b=1, c=2)) try: Model(a=1, b=2) diff --git a/docs/examples/models_required_fields.py b/docs/examples/models_required_fields.py index aee54ae..605a2a0 100644 --- a/docs/examples/models_required_fields.py +++ b/docs/examples/models_required_fields.py @@ -1,5 +1,6 @@ from pydantic import BaseModel, Field + class Model(BaseModel): a: int b: int = ... diff --git a/docs/examples/models_signature.py b/docs/examples/models_signature.py index fb09327..6c0aac0 100644 --- a/docs/examples/models_signature.py +++ b/docs/examples/models_signature.py @@ -1,10 +1,12 @@ import inspect from pydantic import BaseModel, Field + class FooModel(BaseModel): id: int name: str = None description: str = 'Foo' apple: int = Field(..., alias='pear') + print(inspect.signature(FooModel)) diff --git a/docs/examples/models_signature_custom_init.py b/docs/examples/models_signature_custom_init.py index 7caa1d9..7da1fc5 100644 --- a/docs/examples/models_signature_custom_init.py +++ b/docs/examples/models_signature_custom_init.py @@ -2,6 +2,7 @@ import inspect from pydantic import BaseModel + class MyModel(BaseModel): id: int info: str = 'Foo' @@ -10,4 +11,5 @@ class MyModel(BaseModel): """My custom init!""" super().__init__(id=id, bar=bar, **data) + print(inspect.signature(MyModel)) diff --git a/docs/examples/mypy_main.py b/docs/examples/mypy_main.py index 5b22044..8b95e39 100644 --- a/docs/examples/mypy_main.py +++ b/docs/examples/mypy_main.py @@ -3,6 +3,7 @@ from datetime import datetime from typing import List, Optional from pydantic import BaseModel, NoneStr + class Model(BaseModel): age: int first_name = 'John' @@ -10,6 +11,7 @@ class Model(BaseModel): signup_ts: Optional[datetime] = None list_of_ints: List[int] + m = Model(age=42, list_of_ints=[1, '2', b'3']) print(m.middle_name) # not a model field! Model() # will raise a validation error for age and list_of_ints diff --git a/docs/examples/parse_obj_as.py b/docs/examples/parse_obj_as.py index ce91eb1..6f70d74 100644 --- a/docs/examples/parse_obj_as.py +++ b/docs/examples/parse_obj_as.py @@ -2,10 +2,12 @@ from typing import List from pydantic import BaseModel, parse_obj_as + class Item(BaseModel): id: int name: str + # `item_data` could come from an API call, eg., via something like: # item_data = requests.get('https://my-api.com/items').json() item_data = [{'id': 1, 'name': 'My Item'}] diff --git a/docs/examples/postponed_annotations_broken.py b/docs/examples/postponed_annotations_broken.py index d3d68d4..082182a 100644 --- a/docs/examples/postponed_annotations_broken.py +++ b/docs/examples/postponed_annotations_broken.py @@ -1,10 +1,13 @@ from __future__ import annotations from pydantic import BaseModel + def this_is_broken(): # List is defined inside the function so is not in the module's # global scope! from typing import List + class Model(BaseModel): a: List[int] + print(Model(a=(1, 2))) diff --git a/docs/examples/postponed_annotations_forward_ref.py b/docs/examples/postponed_annotations_forward_ref.py index c167e26..3e3377f 100644 --- a/docs/examples/postponed_annotations_forward_ref.py +++ b/docs/examples/postponed_annotations_forward_ref.py @@ -3,10 +3,12 @@ from pydantic import BaseModel Foo = ForwardRef('Foo') + class Foo(BaseModel): a: int = 123 b: Foo = None + Foo.update_forward_refs() print(Foo()) diff --git a/docs/examples/postponed_annotations_main.py b/docs/examples/postponed_annotations_main.py index 99aa7c0..a755f07 100644 --- a/docs/examples/postponed_annotations_main.py +++ b/docs/examples/postponed_annotations_main.py @@ -2,7 +2,9 @@ from __future__ import annotations from typing import List from pydantic import BaseModel + class Model(BaseModel): a: List[int] + print(Model(a=('1', 2, 3))) diff --git a/docs/examples/postponed_annotations_self_referencing_annotations.py b/docs/examples/postponed_annotations_self_referencing_annotations.py index d71710c..902bd62 100644 --- a/docs/examples/postponed_annotations_self_referencing_annotations.py +++ b/docs/examples/postponed_annotations_self_referencing_annotations.py @@ -1,11 +1,13 @@ from __future__ import annotations from pydantic import BaseModel + class Foo(BaseModel): a: int = 123 #: The sibling of `Foo` is referenced directly by type sibling: Foo = None + Foo.update_forward_refs() print(Foo()) diff --git a/docs/examples/postponed_annotations_self_referencing_string.py b/docs/examples/postponed_annotations_self_referencing_string.py index 5ca1cfd..2c918a2 100644 --- a/docs/examples/postponed_annotations_self_referencing_string.py +++ b/docs/examples/postponed_annotations_self_referencing_string.py @@ -1,10 +1,12 @@ from pydantic import BaseModel + class Foo(BaseModel): a: int = 123 #: The sibling of `Foo` is referenced by string sibling: 'Foo' = None + Foo.update_forward_refs() print(Foo()) diff --git a/docs/examples/postponed_annotations_works.py b/docs/examples/postponed_annotations_works.py index a4a8243..eb289a5 100644 --- a/docs/examples/postponed_annotations_works.py +++ b/docs/examples/postponed_annotations_works.py @@ -2,7 +2,9 @@ from __future__ import annotations from typing import List # <-- List is defined in the module's global scope from pydantic import BaseModel + def this_works(): class Model(BaseModel): a: List[int] + print(Model(a=(1, 2))) diff --git a/docs/examples/schema_custom.py b/docs/examples/schema_custom.py index bbd2c39..996cdc0 100644 --- a/docs/examples/schema_custom.py +++ b/docs/examples/schema_custom.py @@ -3,13 +3,15 @@ import json from pydantic import BaseModel from pydantic.schema import schema + class Foo(BaseModel): a: int + class Model(BaseModel): a: Foo + # Default location for OpenAPI top_level_schema = schema([Model], ref_prefix='#/components/schemas/') print(json.dumps(top_level_schema, indent=2)) - diff --git a/docs/examples/schema_extra_callable.py b/docs/examples/schema_extra_callable.py index d48b5a7..2b29655 100644 --- a/docs/examples/schema_extra_callable.py +++ b/docs/examples/schema_extra_callable.py @@ -2,6 +2,7 @@ from typing import Dict, Any, Type from pydantic import BaseModel + class Person(BaseModel): name: str age: int @@ -12,4 +13,5 @@ class Person(BaseModel): for prop in schema.get('properties', {}).values(): prop.pop('title', None) + print(Person.schema_json(indent=2)) diff --git a/docs/examples/schema_main.py b/docs/examples/schema_main.py index 40b20fe..319ae46 100644 --- a/docs/examples/schema_main.py +++ b/docs/examples/schema_main.py @@ -2,20 +2,24 @@ from enum import Enum from pydantic import BaseModel, Field + class FooBar(BaseModel): count: int size: float = None + class Gender(str, Enum): male = 'male' female = 'female' other = 'other' not_given = 'not_given' + class MainModel(BaseModel): """ This is the description of the main model """ + foo_bar: FooBar = Field(...) gender: Gender = Field(None, alias='Gender') snap: int = Field( @@ -29,5 +33,6 @@ class MainModel(BaseModel): class Config: title = 'Main' + # this is equivalent to json.dumps(MainModel.schema(), indent=2): print(MainModel.schema_json(indent=2)) diff --git a/docs/examples/schema_top_level.py b/docs/examples/schema_top_level.py index 77b2e3b..97d9042 100644 --- a/docs/examples/schema_top_level.py +++ b/docs/examples/schema_top_level.py @@ -3,15 +3,18 @@ import json from pydantic import BaseModel from pydantic.schema import schema + class Foo(BaseModel): a: str = None + class Model(BaseModel): b: Foo + class Bar(BaseModel): c: int + top_level_schema = schema([Model, Bar], title='My Schema') print(json.dumps(top_level_schema, indent=2)) - diff --git a/docs/examples/schema_unenforced_constraints.py b/docs/examples/schema_unenforced_constraints.py index baa186f..8addaee 100644 --- a/docs/examples/schema_unenforced_constraints.py +++ b/docs/examples/schema_unenforced_constraints.py @@ -8,13 +8,16 @@ try: except ValueError as e: print(e) + # but you can set the schema attribute directly: # (Note: here exclusiveMaximum will not be enforce) class Model(BaseModel): foo: PositiveInt = Field(..., exclusiveMaximum=10) + print(Model.schema()) + # if you find yourself needing this, an alternative is to declare # the constraints in Field (or you could use conint()) # here both constraints will be enforced: @@ -23,4 +26,5 @@ class Model(BaseModel): # will be generated correctly foo: int = Field(..., gt=0, lt=10) + print(Model.schema()) diff --git a/docs/examples/schema_with_example.py b/docs/examples/schema_with_example.py index ea3995a..3676ac6 100644 --- a/docs/examples/schema_with_example.py +++ b/docs/examples/schema_with_example.py @@ -1,6 +1,7 @@ # output-json from pydantic import BaseModel + class Person(BaseModel): name: str age: int @@ -15,4 +16,5 @@ class Person(BaseModel): ] } + print(Person.schema_json(indent=2)) diff --git a/docs/examples/settings_case_sensitive.py b/docs/examples/settings_case_sensitive.py index b043b7d..5030704 100644 --- a/docs/examples/settings_case_sensitive.py +++ b/docs/examples/settings_case_sensitive.py @@ -1,5 +1,6 @@ from pydantic import BaseSettings + class Settings(BaseSettings): redis_host = 'localhost' diff --git a/docs/examples/settings_main.py b/docs/examples/settings_main.py index 843940f..c2beadc 100644 --- a/docs/examples/settings_main.py +++ b/docs/examples/settings_main.py @@ -1,13 +1,20 @@ from typing import Set from pydantic import ( - BaseModel, BaseSettings, PyObject, RedisDsn, PostgresDsn, Field + BaseModel, + BaseSettings, + PyObject, + RedisDsn, + PostgresDsn, + Field, ) + class SubModel(BaseModel): foo = 'bar' apple = 1 + class Settings(BaseSettings): auth_key: str api_key: str = Field(..., env='my_api_key') @@ -36,4 +43,5 @@ class Settings(BaseSettings): } } + print(Settings().dict()) diff --git a/docs/examples/types_arbitrary_allowed.py b/docs/examples/types_arbitrary_allowed.py index f55168b..14379b4 100644 --- a/docs/examples/types_arbitrary_allowed.py +++ b/docs/examples/types_arbitrary_allowed.py @@ -1,10 +1,12 @@ from pydantic import BaseModel, ValidationError + # This is not a pydantic model, it's an arbitrary class class Pet: def __init__(self, name: str): self.name = name + class Model(BaseModel): pet: Pet owner: str @@ -12,6 +14,7 @@ class Model(BaseModel): class Config: arbitrary_types_allowed = True + pet = Pet(name='Hedwig') # A simple check of instance type is used to validate the data model = Model(owner='Harry', pet=pet) diff --git a/docs/examples/types_bare_type.py b/docs/examples/types_bare_type.py index 3afcf25..b3dec3b 100644 --- a/docs/examples/types_bare_type.py +++ b/docs/examples/types_bare_type.py @@ -2,12 +2,15 @@ from typing import Type from pydantic import BaseModel, ValidationError + class Foo: pass + class LenientSimpleModel(BaseModel): any_class_goes: Type + LenientSimpleModel(any_class_goes=int) LenientSimpleModel(any_class_goes=Foo) try: diff --git a/docs/examples/types_boolean.py b/docs/examples/types_boolean.py index bb2cf8f..6c2d03a 100644 --- a/docs/examples/types_boolean.py +++ b/docs/examples/types_boolean.py @@ -1,8 +1,10 @@ from pydantic import BaseModel, ValidationError + class BooleanModel(BaseModel): bool_value: bool + print(BooleanModel(bool_value=False)) print(BooleanModel(bool_value='False')) try: diff --git a/docs/examples/types_bytesize.py b/docs/examples/types_bytesize.py index 98a290a..55878a8 100644 --- a/docs/examples/types_bytesize.py +++ b/docs/examples/types_bytesize.py @@ -1,8 +1,10 @@ from pydantic import BaseModel, ByteSize + class MyModel(BaseModel): size: ByteSize + print(MyModel(size=52000).size) print(MyModel(size='3000 KiB').size) diff --git a/docs/examples/types_callable.py b/docs/examples/types_callable.py index fb89583..3772a5f 100644 --- a/docs/examples/types_callable.py +++ b/docs/examples/types_callable.py @@ -1,8 +1,10 @@ from typing import Callable from pydantic import BaseModel + class Foo(BaseModel): callback: Callable[[int], int] + m = Foo(callback=lambda x: x) print(m) diff --git a/docs/examples/types_choices.py b/docs/examples/types_choices.py index f4cf3c1..3e3477b 100644 --- a/docs/examples/types_choices.py +++ b/docs/examples/types_choices.py @@ -2,18 +2,22 @@ from enum import Enum, IntEnum from pydantic import BaseModel, ValidationError + class FruitEnum(str, Enum): pear = 'pear' banana = 'banana' + class ToolEnum(IntEnum): spanner = 1 wrench = 2 + class CookingModel(BaseModel): fruit: FruitEnum = FruitEnum.pear tool: ToolEnum = ToolEnum.spanner + print(CookingModel()) print(CookingModel(tool=2, fruit='banana')) try: diff --git a/docs/examples/types_color.py b/docs/examples/types_color.py index c78cb66..705d7d5 100644 --- a/docs/examples/types_color.py +++ b/docs/examples/types_color.py @@ -8,9 +8,12 @@ c2 = Color('green') print(c2.as_rgb_tuple()) print(c2.original()) print(repr(Color('hsl(180, 100%, 50%)'))) + + class Model(BaseModel): color: Color + print(Model(color='purple')) try: Model(color='hello') diff --git a/docs/examples/types_constrained.py b/docs/examples/types_constrained.py index fb3c247..df20783 100644 --- a/docs/examples/types_constrained.py +++ b/docs/examples/types_constrained.py @@ -15,12 +15,13 @@ from pydantic import ( Field, ) + class Model(BaseModel): short_bytes: conbytes(min_length=2, max_length=10) strip_bytes: conbytes(strip_whitespace=True) short_str: constr(min_length=2, max_length=10) - regex_str: constr(regex='^apple (pie|tart|sandwich)$') + regex_str: constr(regex=r'^apple (pie|tart|sandwich)$') strip_str: constr(strip_whitespace=True) big_int: conint(gt=1000, lt=1024) diff --git a/docs/examples/types_custom_type.py b/docs/examples/types_custom_type.py index 5e99d96..f9bbafd 100644 --- a/docs/examples/types_custom_type.py +++ b/docs/examples/types_custom_type.py @@ -15,12 +15,14 @@ post_code_regex = re.compile( r')' ) + class PostCode(str): """ Partial UK postcode validation. Note: this is just an example, and is not intended for use in production; in particular this does NOT guarantee a postcode exists, just that it has a valid format. """ + @classmethod def __get_validators__(cls): # one or more validators may be yielded which will be called in the @@ -55,9 +57,11 @@ class PostCode(str): def __repr__(self): return f'PostCode({super().__repr__()})' + class Model(BaseModel): post_code: PostCode + model = Model(post_code='sw8 5el') print(model) print(model.post_code) diff --git a/docs/examples/types_dt.py b/docs/examples/types_dt.py index f2d0b03..523accb 100644 --- a/docs/examples/types_dt.py +++ b/docs/examples/types_dt.py @@ -1,17 +1,19 @@ from datetime import date, datetime, time, timedelta from pydantic import BaseModel + class Model(BaseModel): d: date = None dt: datetime = None t: time = None td: timedelta = None + m = Model( d=1966280412345.6789, dt='2032-04-23T10:20:30.400+02:30', t=time(4, 8, 16), - td='P3DT12H30M5S' + td='P3DT12H30M5S', ) print(m.dict()) diff --git a/docs/examples/types_generics.py b/docs/examples/types_generics.py index 4d5f7c5..50cfafd 100644 --- a/docs/examples/types_generics.py +++ b/docs/examples/types_generics.py @@ -5,6 +5,7 @@ from typing import TypeVar, Generic AgedType = TypeVar('AgedType') QualityType = TypeVar('QualityType') + # This is not a pydantic model, it's an arbitrary generic class class TastingModel(Generic[AgedType, QualityType]): def __init__(self, name: str, aged: AgedType, quality: QualityType): @@ -43,6 +44,7 @@ class TastingModel(Generic[AgedType, QualityType]): # Validation passed without errors, return the same instance received return v + class Model(BaseModel): # for wine, "aged" is an int with years, "quality" is a float wine: TastingModel[int, float] @@ -51,13 +53,14 @@ class Model(BaseModel): # for thing, "aged" is a Any, "quality" is Any thing: TastingModel + model = Model( # This wine was aged for 20 years and has a quality of 85.6 wine=TastingModel(name='Cabernet Sauvignon', aged=20, quality=85.6), # This cheese is aged (is mature) and has "Good" quality cheese=TastingModel(name='Gouda', aged=True, quality='Good'), # This Python thing has aged "Not much" and has a quality "Awesome" - thing=TastingModel(name='Python', aged='Not much', quality='Awesome') + thing=TastingModel(name='Python', aged='Not much', quality='Awesome'), ) print(model) print(model.wine.aged) @@ -74,7 +77,7 @@ try: cheese=TastingModel(name='Gouda', aged='yeah', quality=5), # For thing, no type parameters are declared, and we skipped validation # in those cases in the Assessment.validate() function - thing=TastingModel(name='Python', aged='Not much', quality='Awesome') + thing=TastingModel(name='Python', aged='Not much', quality='Awesome'), ) except ValidationError as e: print(e) diff --git a/docs/examples/types_infinite_generator.py b/docs/examples/types_infinite_generator.py index fb7a8be..22aa626 100644 --- a/docs/examples/types_infinite_generator.py +++ b/docs/examples/types_infinite_generator.py @@ -1,15 +1,18 @@ from typing import Iterable from pydantic import BaseModel + class Model(BaseModel): infinite: Iterable[int] + def infinite_ints(): i = 0 while True: yield i i += 1 + m = Model(infinite=infinite_ints()) print(m) diff --git a/docs/examples/types_infinite_generator_validate_first.py b/docs/examples/types_infinite_generator_validate_first.py index aaf5485..1325d36 100644 --- a/docs/examples/types_infinite_generator_validate_first.py +++ b/docs/examples/types_infinite_generator_validate_first.py @@ -3,6 +3,7 @@ from typing import Iterable from pydantic import BaseModel, validator, ValidationError from pydantic.fields import ModelField + class Model(BaseModel): infinite: Iterable[int] @@ -22,20 +23,24 @@ class Model(BaseModel): # the rest of the values from the (already started) iterable return itertools.chain([first_value], iterable) + def infinite_ints(): i = 0 while True: yield i i += 1 + m = Model(infinite=infinite_ints()) print(m) + def infinite_strs(): while True: for letter in 'allthesingleladies': yield letter + try: Model(infinite=infinite_strs()) except ValidationError as e: diff --git a/docs/examples/types_iterables.py b/docs/examples/types_iterables.py index 8cc66f4..2babe1c 100644 --- a/docs/examples/types_iterables.py +++ b/docs/examples/types_iterables.py @@ -2,6 +2,7 @@ from typing import Dict, FrozenSet, List, Optional, Sequence, Set, Tuple, Union from pydantic import BaseModel + class Model(BaseModel): simple_list: list = None list_of_ints: List[int] = None @@ -23,6 +24,7 @@ class Model(BaseModel): compound: Dict[Union[str, bytes], List[Set[int]]] = None + print(Model(simple_list=['1', '2', '3']).simple_list) print(Model(list_of_ints=['1', '2', '3']).list_of_ints) diff --git a/docs/examples/types_json_type.py b/docs/examples/types_json_type.py index 26b37ec..7527181 100644 --- a/docs/examples/types_json_type.py +++ b/docs/examples/types_json_type.py @@ -2,12 +2,15 @@ from typing import List from pydantic import BaseModel, Json, ValidationError + class SimpleJsonModel(BaseModel): json_obj: Json + class ComplexJsonModel(BaseModel): json_obj: Json[List[int]] + print(SimpleJsonModel(json_obj='{"b": 1}')) print(ComplexJsonModel(json_obj='[1, 2, 3]')) try: diff --git a/docs/examples/types_literal1.py b/docs/examples/types_literal1.py index 0345ec9..c44a2ea 100644 --- a/docs/examples/types_literal1.py +++ b/docs/examples/types_literal1.py @@ -2,9 +2,11 @@ from typing_extensions import Literal from pydantic import BaseModel, ValidationError + class Pie(BaseModel): flavor: Literal['apple', 'pumpkin'] + Pie(flavor='apple') Pie(flavor='pumpkin') try: diff --git a/docs/examples/types_literal2.py b/docs/examples/types_literal2.py index 6a8f4d8..f0bd127 100644 --- a/docs/examples/types_literal2.py +++ b/docs/examples/types_literal2.py @@ -4,17 +4,21 @@ from typing_extensions import Literal from pydantic import BaseModel, ValidationError + class Cake(BaseModel): kind: Literal['cake'] required_utensils: ClassVar[List[str]] = ['fork', 'knife'] + class IceCream(BaseModel): kind: Literal['icecream'] required_utensils: ClassVar[List[str]] = ['spoon'] + class Meal(BaseModel): dessert: Union[Cake, IceCream] + print(type(Meal(dessert={'kind': 'cake'}).dessert).__name__) print(type(Meal(dessert={'kind': 'icecream'}).dessert).__name__) try: diff --git a/docs/examples/types_literal3.py b/docs/examples/types_literal3.py index 892d8ab..48fc117 100644 --- a/docs/examples/types_literal3.py +++ b/docs/examples/types_literal3.py @@ -4,22 +4,28 @@ from typing_extensions import Literal from pydantic import BaseModel + class Dessert(BaseModel): kind: str + class Pie(Dessert): kind: Literal['pie'] flavor: Optional[str] + class ApplePie(Pie): flavor: Literal['apple'] + class PumpkinPie(Pie): flavor: Literal['pumpkin'] + class Meal(BaseModel): dessert: Union[ApplePie, PumpkinPie, Pie, Dessert] + print(type(Meal(dessert={'kind': 'pie', 'flavor': 'apple'}).dessert).__name__) print(type(Meal(dessert={'kind': 'pie', 'flavor': 'pumpkin'}).dessert).__name__) print(type(Meal(dessert={'kind': 'pie'}).dessert).__name__) diff --git a/docs/examples/types_payment_card_number.py b/docs/examples/types_payment_card_number.py index b66e2c2..22d93fe 100644 --- a/docs/examples/types_payment_card_number.py +++ b/docs/examples/types_payment_card_number.py @@ -3,6 +3,7 @@ from datetime import date from pydantic import BaseModel from pydantic.types import PaymentCardBrand, PaymentCardNumber, constr + class Card(BaseModel): name: constr(strip_whitespace=True, min_length=1) number: PaymentCardNumber @@ -16,10 +17,11 @@ class Card(BaseModel): def expired(self) -> bool: return self.exp < date.today() + card = Card( name='Georg Wilhelm Friedrich Hegel', number='4000000000000002', - exp=date(2023, 9, 30) + exp=date(2023, 9, 30), ) assert card.number.brand == PaymentCardBrand.visa diff --git a/docs/examples/types_secret_types.py b/docs/examples/types_secret_types.py index cede3c1..0a4b404 100644 --- a/docs/examples/types_secret_types.py +++ b/docs/examples/types_secret_types.py @@ -1,9 +1,11 @@ from pydantic import BaseModel, SecretStr, SecretBytes, ValidationError + class SimpleModel(BaseModel): password: SecretStr password_bytes: SecretBytes + sm = SimpleModel(password='IAmSensitive', password_bytes=b'IAmSensitiveBytes') # Standard access methods will not display the secret @@ -21,6 +23,7 @@ try: except ValidationError as e: print(e) + # If you want the secret to be dumped as plain-text using the json method, # you can use json_encoders in the Config class. class SimpleModelDumpable(BaseModel): @@ -33,8 +36,10 @@ class SimpleModelDumpable(BaseModel): SecretBytes: lambda v: v.get_secret_value() if v else None, } -sm2 = SimpleModelDumpable(password='IAmSensitive', - password_bytes=b'IAmSensitiveBytes') + +sm2 = SimpleModelDumpable( + password='IAmSensitive', password_bytes=b'IAmSensitiveBytes' +) # Standard access methods will not display the secret print(sm2) diff --git a/docs/examples/types_strict.py b/docs/examples/types_strict.py index ce853da..28f607b 100644 --- a/docs/examples/types_strict.py +++ b/docs/examples/types_strict.py @@ -1,18 +1,20 @@ -from pydantic import ( - BaseModel, confloat, StrictBool, StrictInt, ValidationError -) +from pydantic import BaseModel, StrictBool, StrictInt, ValidationError, confloat + class StrictIntModel(BaseModel): strict_int: StrictInt + try: StrictIntModel(strict_int=3.14159) except ValidationError as e: print(e) + class ConstrainedFloatModel(BaseModel): constrained_float: confloat(strict=True, ge=0.0) + try: ConstrainedFloatModel(constrained_float=3) except ValidationError as e: @@ -23,9 +25,11 @@ try: except ValidationError as e: print(e) + class StrictBoolModel(BaseModel): strict_bool: StrictBool + try: StrictBoolModel(strict_bool='False') except ValidationError as e: diff --git a/docs/examples/types_type.py b/docs/examples/types_type.py index b2a1dc9..933d7ee 100644 --- a/docs/examples/types_type.py +++ b/docs/examples/types_type.py @@ -3,18 +3,23 @@ from typing import Type from pydantic import BaseModel from pydantic import ValidationError + class Foo: pass + class Bar(Foo): pass + class Other: pass + class SimpleModel(BaseModel): just_subclasses: Type[Foo] + SimpleModel(just_subclasses=Foo) SimpleModel(just_subclasses=Bar) try: diff --git a/docs/examples/types_typevar.py b/docs/examples/types_typevar.py index c8c34f6..85dc563 100644 --- a/docs/examples/types_typevar.py +++ b/docs/examples/types_typevar.py @@ -5,11 +5,13 @@ Foobar = TypeVar('Foobar') BoundFloat = TypeVar('BoundFloat', bound=float) IntStr = TypeVar('IntStr', int, str) + class Model(BaseModel): a: Foobar # equivalent of ": Any" b: BoundFloat # equivalent of ": float" c: IntStr # equivalent of ": Union[int, str]" + print(Model(a=[1], b=4.2, c='x')) # a may be None and is therefore optional diff --git a/docs/examples/types_union_correct.py b/docs/examples/types_union_correct.py index 77c4601..9a4283f 100644 --- a/docs/examples/types_union_correct.py +++ b/docs/examples/types_union_correct.py @@ -2,10 +2,12 @@ from uuid import UUID from typing import Union from pydantic import BaseModel + class User(BaseModel): id: Union[UUID, int, str] name: str + user_03_uuid = UUID('cf57432e-809e-4353-adbd-9d5c0d733868') user_03 = User(id=user_03_uuid, name='John Doe') print(user_03) diff --git a/docs/examples/types_union_incorrect.py b/docs/examples/types_union_incorrect.py index c0454c8..f493f78 100644 --- a/docs/examples/types_union_incorrect.py +++ b/docs/examples/types_union_incorrect.py @@ -2,10 +2,12 @@ from uuid import UUID from typing import Union from pydantic import BaseModel + class User(BaseModel): id: Union[int, str, UUID] name: str + user_01 = User(id=123, name='John Doe') print(user_01) print(user_01.id) diff --git a/docs/examples/types_url_properties.py b/docs/examples/types_url_properties.py index 8e0f8ae..f2885ac 100644 --- a/docs/examples/types_url_properties.py +++ b/docs/examples/types_url_properties.py @@ -1,8 +1,10 @@ from pydantic import BaseModel, HttpUrl, PostgresDsn, ValidationError, validator + class MyModel(BaseModel): url: HttpUrl + m = MyModel(url='http://www.example.com') # the repr() method for a url will display all properties of the url @@ -11,6 +13,8 @@ print(m.url.scheme) print(m.url.host) print(m.url.host_type) print(m.url.port) + + class MyDatabaseModel(BaseModel): db: PostgresDsn @@ -19,6 +23,7 @@ class MyDatabaseModel(BaseModel): assert v.path and len(v.path) > 1, 'database must be provided' return v + m = MyDatabaseModel(db='postgres://user:pass@localhost:5432/foobar') print(m.db) @@ -26,4 +31,3 @@ try: MyDatabaseModel(db='postgres://user:pass@localhost:5432') except ValidationError as e: print(e) - diff --git a/docs/examples/types_url_punycode.py b/docs/examples/types_url_punycode.py index c18f2f4..31dd85f 100644 --- a/docs/examples/types_url_punycode.py +++ b/docs/examples/types_url_punycode.py @@ -1,8 +1,10 @@ from pydantic import BaseModel, HttpUrl + class MyModel(BaseModel): url: HttpUrl + m1 = MyModel(url='http://puny£code.com') print(m1.url) print(m1.url.host_type) diff --git a/docs/examples/types_urls.py b/docs/examples/types_urls.py index 0158552..9874d3a 100644 --- a/docs/examples/types_urls.py +++ b/docs/examples/types_urls.py @@ -1,8 +1,10 @@ from pydantic import BaseModel, HttpUrl, ValidationError + class MyModel(BaseModel): url: HttpUrl + m = MyModel(url='http://www.example.com') print(m.url) try: diff --git a/docs/examples/validation_decorator_async.py b/docs/examples/validation_decorator_async.py index e268440..41bbe6c 100644 --- a/docs/examples/validation_decorator_async.py +++ b/docs/examples/validation_decorator_async.py @@ -2,11 +2,13 @@ class Connection: async def execute(self, sql, *args): return 'testing@example.com' + conn = Connection() # ignore-above import asyncio from pydantic import PositiveInt, ValidationError, validate_arguments + @validate_arguments async def get_user_email(user_id: PositiveInt): # `conn` is some fictional connection to a database @@ -16,6 +18,7 @@ async def get_user_email(user_id: PositiveInt): else: return email + async def main(): email = await get_user_email(123) print(email) @@ -24,4 +27,5 @@ async def main(): except ValidationError as exc: print(exc.errors()) + asyncio.run(main()) diff --git a/docs/examples/validation_decorator_main.py b/docs/examples/validation_decorator_main.py index 5bc6ad1..b260a43 100644 --- a/docs/examples/validation_decorator_main.py +++ b/docs/examples/validation_decorator_main.py @@ -1,10 +1,12 @@ from pydantic import validate_arguments, ValidationError + @validate_arguments def repeat(s: str, count: int, *, separator: bytes = b'') -> bytes: b = s.encode() return separator.join(b for _ in range(count)) + a = repeat('hello', 3) print(a) diff --git a/docs/examples/validation_decorator_parameter_types.py b/docs/examples/validation_decorator_parameter_types.py index 0da753a..0f80133 100644 --- a/docs/examples/validation_decorator_parameter_types.py +++ b/docs/examples/validation_decorator_parameter_types.py @@ -1,44 +1,55 @@ # requires python3.8 from pydantic import validate_arguments + @validate_arguments def pos_or_kw(a: int, b: int = 2) -> str: return f'a={a} b={b}' + print(pos_or_kw(1)) print(pos_or_kw(a=1)) print(pos_or_kw(1, 3)) print(pos_or_kw(a=1, b=3)) + @validate_arguments def kw_only(*, a: int, b: int = 2) -> str: return f'a={a} b={b}' + print(kw_only(a=1)) print(kw_only(a=1, b=3)) + @validate_arguments def pos_only(a: int, b: int = 2, /) -> str: # python 3.8 only return f'a={a} b={b}' + print(pos_only(1)) print(pos_only(1, 2)) + @validate_arguments def var_args(*args: int) -> str: return str(args) + print(var_args(1)) print(var_args(1, 2)) print(var_args(1, 2, 3)) + @validate_arguments def var_kwargs(**kwargs: int) -> str: return str(kwargs) + print(var_kwargs(a=1)) print(var_kwargs(a=1, b=2)) + @validate_arguments def armageddon( a: int, @@ -48,9 +59,10 @@ def armageddon( *d: int, e: int, f: int = None, - **g: int + **g: int, ) -> str: return f'a={a} b={b} c={c} d={d} e={e} f={f} g={g}' + print(armageddon(1, 2, e=3)) print(armageddon(1, 2, 3, 4, 5, 6, c=7, e=8, f=9, g=10, spam=11)) diff --git a/docs/examples/validation_decorator_raw_function.py b/docs/examples/validation_decorator_raw_function.py index 47d649c..8e76fd4 100644 --- a/docs/examples/validation_decorator_raw_function.py +++ b/docs/examples/validation_decorator_raw_function.py @@ -1,10 +1,12 @@ from pydantic import validate_arguments + @validate_arguments def repeat(s: str, count: int, *, separator: bytes = b'') -> bytes: b = s.encode() return separator.join(b for _ in range(count)) + a = repeat('hello', 3) print(a) diff --git a/docs/examples/validation_decorator_types.py b/docs/examples/validation_decorator_types.py index ffcdb5d..de8752e 100644 --- a/docs/examples/validation_decorator_types.py +++ b/docs/examples/validation_decorator_types.py @@ -3,6 +3,7 @@ from typing import Pattern, Optional from pydantic import validate_arguments, DirectoryPath + @validate_arguments def find_file(path: DirectoryPath, regex: Pattern, max=None) -> Optional[Path]: for i, f in enumerate(path.glob('**/*')): @@ -11,5 +12,6 @@ def find_file(path: DirectoryPath, regex: Pattern, max=None) -> Optional[Path]: if f.is_file() and regex.fullmatch(str(f.relative_to(path))): return f + print(find_file('/etc/', '^sys.*')) print(find_file('/etc/', '^foobar.*', max=3)) diff --git a/docs/examples/validators_allow_reuse.py b/docs/examples/validators_allow_reuse.py index 723b6f3..c6f52f3 100644 --- a/docs/examples/validators_allow_reuse.py +++ b/docs/examples/validators_allow_reuse.py @@ -1,20 +1,24 @@ from pydantic import BaseModel, validator + def normalize(name: str) -> str: return ' '.join((word.capitalize()) for word in name.split(' ')) + class Producer(BaseModel): name: str # validators _normalize_name = validator('name', allow_reuse=True)(normalize) + class Consumer(BaseModel): name: str # validators _normalize_name = validator('name', allow_reuse=True)(normalize) + jane_doe = Producer(name='JaNe DOE') john_doe = Consumer(name='joHN dOe') assert jane_doe.name == 'Jane Doe' diff --git a/docs/examples/validators_always.py b/docs/examples/validators_always.py index 838dc60..f829c68 100644 --- a/docs/examples/validators_always.py +++ b/docs/examples/validators_always.py @@ -2,6 +2,7 @@ from datetime import datetime from pydantic import BaseModel, validator + class DemoModel(BaseModel): ts: datetime = None @@ -9,5 +10,6 @@ class DemoModel(BaseModel): def set_ts_now(cls, v): return v or datetime.now() + print(DemoModel()) print(DemoModel(ts='2017-11-08T14:00')) diff --git a/docs/examples/validators_dataclass.py b/docs/examples/validators_dataclass.py index 389a00b..11db5fc 100644 --- a/docs/examples/validators_dataclass.py +++ b/docs/examples/validators_dataclass.py @@ -3,6 +3,7 @@ from datetime import datetime from pydantic import validator from pydantic.dataclasses import dataclass + @dataclass class DemoDataclass: ts: datetime = None @@ -11,5 +12,6 @@ class DemoDataclass: def set_ts_now(cls, v): return v or datetime.now() + print(DemoDataclass()) print(DemoDataclass(ts='2017-11-08T14:00')) diff --git a/docs/examples/validators_pre_item.py b/docs/examples/validators_pre_item.py index 207e042..255712d 100644 --- a/docs/examples/validators_pre_item.py +++ b/docs/examples/validators_pre_item.py @@ -1,6 +1,7 @@ from typing import List from pydantic import BaseModel, ValidationError, validator + class DemoModel(BaseModel): square_numbers: List[int] = [] cube_numbers: List[int] = [] @@ -15,7 +16,7 @@ class DemoModel(BaseModel): @validator('cube_numbers', 'square_numbers') def check_sum(cls, v): if sum(v) > 42: - raise ValueError(f'sum of numbers greater than 42') + raise ValueError('sum of numbers greater than 42') return v @validator('square_numbers', each_item=True) @@ -30,6 +31,7 @@ class DemoModel(BaseModel): assert v ** (1 / 3) % 1 == 0, f'{v} is not a cubed number' return v + print(DemoModel(square_numbers=[1, 4, 9])) print(DemoModel(square_numbers='1|4|16')) print(DemoModel(square_numbers=[16], cube_numbers=[8, 27])) @@ -42,4 +44,3 @@ try: DemoModel(cube_numbers=[27, 27]) except ValidationError as e: print(e) - diff --git a/docs/examples/validators_root.py b/docs/examples/validators_root.py index afd829c..010c52a 100644 --- a/docs/examples/validators_root.py +++ b/docs/examples/validators_root.py @@ -1,5 +1,6 @@ from pydantic import BaseModel, ValidationError, root_validator + class UserModel(BaseModel): username: str password1: str @@ -17,6 +18,7 @@ class UserModel(BaseModel): raise ValueError('passwords do not match') return values + print(UserModel(username='scolvin', password1='zxcvbn', password2='zxcvbn')) try: UserModel(username='scolvin', password1='zxcvbn', password2='zxcvbn2') @@ -24,7 +26,11 @@ except ValidationError as e: print(e) try: - UserModel(username='scolvin', password1='zxcvbn', password2='zxcvbn', - card_number='1234') + UserModel( + username='scolvin', + password1='zxcvbn', + password2='zxcvbn', + card_number='1234', + ) except ValidationError as e: print(e) diff --git a/docs/examples/validators_simple.py b/docs/examples/validators_simple.py index 247b7e1..8f78917 100644 --- a/docs/examples/validators_simple.py +++ b/docs/examples/validators_simple.py @@ -1,5 +1,6 @@ from pydantic import BaseModel, ValidationError, validator + class UserModel(BaseModel): name: str username: str @@ -23,11 +24,21 @@ class UserModel(BaseModel): assert v.isalpha(), 'must be alphanumeric' return v -print(UserModel(name='samuel colvin', username='scolvin', password1='zxcvbn', - password2='zxcvbn')) + +user = UserModel( + name='samuel colvin', + username='scolvin', + password1='zxcvbn', + password2='zxcvbn', +) +print(user) try: - UserModel(name='samuel', username='scolvin', password1='zxcvbn', - password2='zxcvbn2') + UserModel( + name='samuel', + username='scolvin', + password1='zxcvbn', + password2='zxcvbn2', + ) except ValidationError as e: print(e) diff --git a/setup.cfg b/setup.cfg index 1692071..a2947c2 100644 --- a/setup.cfg +++ b/setup.cfg @@ -11,6 +11,10 @@ max-complexity = 14 inline-quotes = single multiline-quotes = double ignore = E203, W503 +per-file-ignores = + docs/examples/schema_unenforced_constraints.py: F811 + docs/examples/validation_decorator_async.py: E402 + docs/examples/types_constrained.py: F722 [bdist_wheel] python-tag = py36.py37.py38