gurudesh/pytracebugs huggingface dataset:
# Buggy code
def list_length_validator(
    cls, v: "Optional[List[T]]", field: "ModelField"
) -> "Optional[List[T]]":
    if v is None and not field.required:
        return None

    v = list_validator(v)
    v_len = len(v)

    if cls.min_items is not None and v_len < cls.min_items:
        raise errors.ListMinLengthError(limit_value=cls.min_items)

    if cls.max_items is not None and v_len > cls.max_items:
        raise errors.ListMaxLengthError(limit_value=cls.max_items)

    return v


# Traceback (pydantic.error_wrappers.ValidationError)
Info model set: network_segments=None
Info model conset: network_segments=None
Info settings set: network_segments=None

Traceback (most recent call last):
File "/home/mihai/bug.py", line 25, in <module>
print(f"Info settings conset: {InfoSettingsConset()}")
File "pydantic/env_settings.py", line 34, in pydantic.env_settings.BaseSettings.__init__
File "pydantic/main.py", line 362, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for InfoSettingsConset
network_segments
value is not a valid set (type=type_error.set)

# Fixed code
def list_length_validator(cls, v: "Optional[List[T]]") -> "Optional[List[T]]":
    if v is None:
        return None

    v = list_validator(v)
    v_len = len(v)

    if cls.min_items is not None and v_len < cls.min_items:
        raise errors.ListMinLengthError(limit_value=cls.min_items)

    if cls.max_items is not None and v_len > cls.max_items:
        raise errors.ListMaxLengthError(limit_value=cls.max_items)

    return v
# Buggy code
def set_length_validator(
    cls, v: "Optional[Set[T]]", field: "ModelField"
) -> "Optional[Set[T]]":
    v = set_validator(v)
    v_len = len(v)

    if cls.min_items is not None and v_len < cls.min_items:
        raise errors.SetMinLengthError(limit_value=cls.min_items)

    if cls.max_items is not None and v_len > cls.max_items:
        raise errors.SetMaxLengthError(limit_value=cls.max_items)

    return v


# Traceback (pydantic.error_wrappers.ValidationError)
Info model set: network_segments=None
Info model conset: network_segments=None
Info settings set: network_segments=None

Traceback (most recent call last):
File "/home/mihai/bug.py", line 25, in <module>
print(f"Info settings conset: {InfoSettingsConset()}")
File "pydantic/env_settings.py", line 34, in pydantic.env_settings.BaseSettings.__init__
File "pydantic/main.py", line 362, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for InfoSettingsConset
network_segments
value is not a valid set (type=type_error.set)

# Fixed code
def set_length_validator(cls, v: "Optional[Set[T]]") -> "Optional[Set[T]]":
    if v is None:
        return None

    v = set_validator(v)
    v_len = len(v)

    if cls.min_items is not None and v_len < cls.min_items:
        raise errors.SetMinLengthError(limit_value=cls.min_items)

    if cls.max_items is not None and v_len > cls.max_items:
        raise errors.SetMaxLengthError(limit_value=cls.max_items)

    return v
# Buggy code
def build_values(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Dict[str, Any]:
    values: Dict[str, Any] = {}
    if args:
        arg_iter = enumerate(args)
        while True:
            try:
                i, a = next(arg_iter)
            except StopIteration:
                break
            arg_name = self.arg_mapping.get(i)
            if arg_name is not None:
                values[arg_name] = a
            else:
                values[self.v_args_name] = [a] + [a for _, a in arg_iter]
                break

    var_kwargs = {}
    wrong_positional_args = []
    non_var_fields = set(self.model.__fields__) - {self.v_args_name, self.v_kwargs_name}
    for k, v in kwargs.items():
        if k in non_var_fields:
            if k in self.positional_only_args:
                wrong_positional_args.append(k)
            values[k] = v
        else:
            var_kwargs[k] = v

    if var_kwargs:
        values[self.v_kwargs_name] = var_kwargs
    if wrong_positional_args:
        values[V_POSITIONAL_ONLY_NAME] = wrong_positional_args
    return values


# Traceback (TypeError)
from pydantic import validate_arguments


@validate_arguments
def foo(x: int):
print(x)


def bar(x: int):
print(x)

foo(1)
1
foo(1, x=2)
2

bar(1)
1
bar(1, x=2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() got multiple values for argument 'x'

# Fixed code
def build_values(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Dict[str, Any]:
    values: Dict[str, Any] = {}
    if args:
        arg_iter = enumerate(args)
        while True:
            try:
                i, a = next(arg_iter)
            except StopIteration:
                break
            arg_name = self.arg_mapping.get(i)
            if arg_name is not None:
                values[arg_name] = a
            else:
                values[self.v_args_name] = [a] + [a for _, a in arg_iter]
                break

    var_kwargs = {}
    wrong_positional_args = []
    duplicate_kwargs = []
    non_var_fields = set(self.model.__fields__) - {self.v_args_name, self.v_kwargs_name}
    for k, v in kwargs.items():
        if k in non_var_fields:
            if k in self.positional_only_args:
                wrong_positional_args.append(k)
            if k in values:
                duplicate_kwargs.append(k)
            values[k] = v
        else:
            var_kwargs[k] = v

    if var_kwargs:
        values[self.v_kwargs_name] = var_kwargs
    if wrong_positional_args:
        values[V_POSITIONAL_ONLY_NAME] = wrong_positional_args
    if duplicate_kwargs:
        values[V_DUPLICATE_KWARGS] = duplicate_kwargs
    return values
# Buggy code
def is_valid_private_name(name: str) -> bool:
    return not is_valid_field(name) and name not in {
        "__annotations__",
        "__classcell__",
        "__doc__",
        "__module__",
        "__qualname__",
    }


# Traceback (TypeError)
TypeError                                 Traceback (most recent call last)
<ipython-input-17-86d3af5f0365> in <module>
----> 1 class Model(GenericModel, Generic[T]):
2     class Config:
3         underscore_attrs_are_private = True
4     id: T
5

/nix/store/5mlyrz5jm75dbjd92wsq89b9lsd0bhww-python3-3.7.7-env/lib/python3.7/site-packages/pydantic/main.py in __new__(mcs, name, bases, namespace, **kwargs)
322         }
323
--> 324         cls = super().__new__(mcs, name, bases, new_namespace, **kwargs)
325         # set __signature__ attr only for model class, but not for its instances
326         cls.__signature__ = ClassAttribute('__signature__', generate_model_signature(cls.__init__, fields, config))

/nix/store/k2w1idz2vdag50xl88113845mr74z823-python3-3.7.7/lib/python3.7/abc.py in __new__(mcls, name, bases, namespace, **kwargs)
124         """
125         def __new__(mcls, name, bases, namespace, **kwargs):
--> 126             cls = super().__new__(mcls, name, bases, namespace, **kwargs)
127             _abc_init(cls)
128             return cls

/nix/store/k2w1idz2vdag50xl88113845mr74z823-python3-3.7.7/lib/python3.7/typing.py in __init_subclass__(cls, *args, **kwargs)
848         tvars = []
849         if '__orig_bases__' in cls.__dict__:
--> 850             error = Generic in cls.__orig_bases__
851         else:
852             error = Generic in cls.__bases__ and cls.__name__ != '_Protocol'

TypeError: argument of type 'member_descriptor' is not iterable

# Fixed code
def is_valid_private_name(name: str) -> bool:
    return not is_valid_field(name) and name not in {
        "__annotations__",
        "__classcell__",
        "__doc__",
        "__module__",
        "__orig_bases__",
        "__qualname__",
    }
# Buggy code
def make_dataclass_validator(
    _cls: Type[Any], config: Type["BaseConfig"]
) -> "CallableGenerator":
    """
    Create a pydantic.dataclass from a builtin dataclass to add type validation
    and yield the validators
    """
    cls = dataclass(_cls, config=config)
    yield from _get_validators(cls)


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/user/debug_pydantic.py", line 11, in <module>
class Example(BaseModel):
File "pydantic/main.py", line 262, in pydantic.main.ModelMetaclass.__new__
File "pydantic/fields.py", line 315, in pydantic.fields.ModelField.infer
File "pydantic/fields.py", line 284, in pydantic.fields.ModelField.__init__
File "pydantic/fields.py", line 362, in pydantic.fields.ModelField.prepare
File "pydantic/fields.py", line 538, in pydantic.fields.ModelField.populate_validators
File "pydantic/validators.py", line 596, in find_validators
File "pydantic/dataclasses.py", line 222, in make_dataclass_validator
# and only from the field() function, although Field instances are
File "pydantic/dataclasses.py", line 214, in pydantic.dataclasses.dataclass
type_name = self.type.__name__
File "pydantic/dataclasses.py", line 209, in pydantic.dataclasses.dataclass.wrap
def __init__(self, type):
File "pydantic/dataclasses.py", line 126, in pydantic.dataclasses._process_class
# +=======+=======+=======+========+========+
File "/home/user/miniconda3/envs/debug_pydantic/lib/python3.8/dataclasses.py", line 1019, in dataclass
return wrap(cls)
File "/home/user/miniconda3/envs/debug_pydantic/lib/python3.8/dataclasses.py", line 1011, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
File "/home/user/miniconda3/envs/debug_pydantic/lib/python3.8/dataclasses.py", line 891, in _process_class
raise TypeError('cannot inherit non-frozen dataclass from a '
TypeError: cannot inherit non-frozen dataclass from a frozen one

# Fixed code
def make_dataclass_validator(
    _cls: Type[Any], config: Type["BaseConfig"]
) -> "CallableGenerator":
    """
    Create a pydantic.dataclass from a builtin dataclass to add type validation
    and yield the validators
    It retrieves the parameters of the dataclass and forwards them to the newly created dataclass
    """
    dataclass_params = _cls.__dataclass_params__
    stdlib_dataclass_parameters = {
        param: getattr(dataclass_params, param) for param in dataclass_params.__slots__
    }
    cls = dataclass(_cls, config=config, **stdlib_dataclass_parameters)
    yield from _get_validators(cls)
# Buggy code
def make_dataclass_validator(_cls: Type[Any], **kwargs: Any) -> "CallableGenerator":
    """
    Create a pydantic.dataclass from a builtin dataclass to add type validation
    and yield the validators
    """
    cls = dataclass(_cls, **kwargs)
    yield from _get_validators(cls)


# Traceback (TypeError)
Traceback (most recent call last):
File "dataclass.py", line 15, in <module>
@dataclass
File "pydantic/dataclasses.py", line 214, in pydantic.dataclasses.dataclass
# name and type are filled in after the fact, not in __init__.
File "pydantic/dataclasses.py", line 209, in pydantic.dataclasses.dataclass.wrap

File "pydantic/dataclasses.py", line 138, in pydantic.dataclasses._process_class
# +-------+-------+-------+--------+--------+
File "dataclass.py", line 17, in <lambda>
a: A = field(default_factory=lambda: A(x=2, y=3))
TypeError: __init__() got an unexpected keyword argument 'x'

# Fixed code
def make_dataclass_validator(
    _cls: Type[Any], config: Type["BaseConfig"]
) -> "CallableGenerator":
    """
    Create a pydantic.dataclass from a builtin dataclass to add type validation
    and yield the validators
    """
    cls = dataclass(_cls, config=config)
    yield from _get_validators(cls)
# Buggy code
def is_valid_private_name(name: str) -> bool:
    return not is_valid_field(name) and name not in {
        "__annotations__",
        "__module__",
        "__annotations__",
        "__qualname__",
    }


# Traceback (TypeError)
test.py:4: DeprecationWarning: __class__ not set defining 'TestObject' as <class '__main__.TestObject'>. Was __classcell__ propagated to type.__new__?
class TestObject(BaseModel):
Traceback (most recent call last):
File "test.py", line 15, in <module>
print(TestObject(public_field="foo"))
File "test.py", line 12, in __init__
super().__init__(**data)
File "pydantic/main.py", line 365, in pydantic.main.BaseModel.__init__
File "pydantic/main.py", line 424, in pydantic.main.BaseModel._init_private_attributes
File "pydantic/fields.py", line 821, in pydantic.fields.PrivateAttr.get_default
File "pydantic/utils.py", line 624, in pydantic.utils.smart_deepcopy
File "/Users/ahedges/.pyenv/versions/3.7.8/lib/python3.7/copy.py", line 169, in deepcopy
rv = reductor(4)
TypeError: can't pickle cell objects

# Fixed code
def is_valid_private_name(name: str) -> bool:
    return not is_valid_field(name) and name not in {
        "__annotations__",
        "__classcell__",
        "__module__",
        "__qualname__",
    }
# Buggy code
def __init__(
    self, value: Any, items: Union["AbstractSetIntStr", "MappingIntStrAny"]
) -> None:
    if TYPE_CHECKING:
        self._items: Union["AbstractSetIntStr", "MappingIntStrAny"]
        self._type: Type[Union[set, dict]]  # type: ignore

    # For further type checks speed-up
    if isinstance(items, dict):
        self._type = dict
    elif isinstance(items, AbstractSet):
        self._type = set
    else:
        raise TypeError(f"Unexpected type of exclude value {items.__class__}")

    if isinstance(value, (list, tuple)):
        try:
            items = self._normalize_indexes(items, len(value))
        except TypeError as e:
            raise TypeError(
                "Excluding fields from a sequence of sub-models or dicts must be performed index-wise: "
                'expected integer keys or keyword "__all__"'
            ) from e

    self._items = items


# Traceback (TypeError)
FullArgSpec(args=['self'], varargs=None, varkw=None, defaults=None, kwonlyargs=['foo'], kwonlydefaults=None, annotations={'foo': <class 'str'>})
Traceback (most recent call last):
File "/usr/lib/python3.8/inspect.py", line 1123, in getfullargspec
sig = _signature_from_callable(func,
File "/usr/lib/python3.8/inspect.py", line 2216, in _signature_from_callable
raise TypeError('{!r} is not a callable object'.format(obj))
TypeError: <__main__.MyModel object at 0x7fb1f405b490> is not a callable object

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/jrootjunior/work/aiogram3/expetiment.py", line 19, in <module>
print(inspect.getfullargspec(MyModel(foo="baz")))
File "/usr/lib/python3.8/inspect.py", line 1132, in getfullargspec
raise TypeError('unsupported callable') from ex
TypeError: unsupported callable

# Fixed code
def __init__(self, name: str, value: Any) -> None:
    self.name = name
    self.value = value
# Buggy code
def __get_validators__(cls) -> "CallableGenerator":
    yield list_validator
    yield cls.list_length_validator


# Traceback (pydantic.error_wrappers.ValidationError)
class Foo(BaseModel):
...     bar: List = Field(None)
...     baz: List = Field(None, max_items=10)
...
Foo()
Foo(bar=None, baz=None)
Foo(bar=None)
Foo(bar=None, baz=None)
Foo(baz=None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/spike/.pyenv/versions/3.8.2/lib/python3.8/site-packages/pydantic/main.py", line 283, in __init__
raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for Foo
baz
value is not a valid list (type=type_error.list)

# Fixed code
def __get_validators__(cls) -> "CallableGenerator":
    yield cls.list_length_validator
# Buggy code
def list_length_validator(cls, v: "List[T]") -> "List[T]":
    v_len = len(v)

    if cls.min_items is not None and v_len < cls.min_items:
        raise errors.ListMinLengthError(limit_value=cls.min_items)

    if cls.max_items is not None and v_len > cls.max_items:
        raise errors.ListMaxLengthError(limit_value=cls.max_items)

    return v


# Traceback (pydantic.error_wrappers.ValidationError)
class Foo(BaseModel):
...     bar: List = Field(None)
...     baz: List = Field(None, max_items=10)
...
Foo()
Foo(bar=None, baz=None)
Foo(bar=None)
Foo(bar=None, baz=None)
Foo(baz=None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/spike/.pyenv/versions/3.8.2/lib/python3.8/site-packages/pydantic/main.py", line 283, in __init__
raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for Foo
baz
value is not a valid list (type=type_error.list)

# Fixed code
def list_length_validator(
    cls, v: "Optional[List[T]]", field: "ModelField"
) -> "Optional[List[T]]":
    if v is None and not field.required:
        return None

    v = list_validator(v)
    v_len = len(v)

    if cls.min_items is not None and v_len < cls.min_items:
        raise errors.ListMinLengthError(limit_value=cls.min_items)

    if cls.max_items is not None and v_len > cls.max_items:
        raise errors.ListMaxLengthError(limit_value=cls.max_items)

    return v
# Buggy code
def validate(cls: Type["Model"], value: Any) -> "Model":
    if isinstance(value, dict):
        return cls(**value)
    elif isinstance(value, cls):
        return value.copy()
    elif cls.__config__.orm_mode:
        return cls.from_orm(value)
    else:
        try:
            value_as_dict = dict(value)
        except (TypeError, ValueError) as e:
            raise DictError() from e
        return cls(**value_as_dict)


# Traceback (pydantic.error_wrappers.ValidationError)
from pydantic import BaseModel

class OperationData(BaseModel):
id: str

class Operation(BaseModel):
__root__: Tuple[int, OperationData]

data = [0, {'id': '1.11.0'}]
# this one works as expected
print(Operation.parse_obj(data))
# printed: __root__=(0, OperationData(id='1.11.0'))

# However, this one doesn't
print(parse_obj_as(Operation, data))
# Traceback (most recent call last):
#  File "/home/**removed**/protocol/base.py", line 238, in <module>
#    print(parse_obj_as(Operation, data))
#  File "pydantic/tools.py", line 35, in pydantic.tools.parse_obj_as
#  File "pydantic/main.py", line 283, in pydantic.main.BaseModel.__init__
# pydantic.error_wrappers.ValidationError: 1 validation error for ParsingModel[Operation]
#__root__
# value is not a valid dict (type=type_error.dict)

# Which is not a big problem. The problem is that I have nested class

class OperationsBatch(BaseModel):
batch_desc: str
operations: List[Operation]

# and it produces same exception on
print(OperationsBatch.parse_obj({'batch_desc': '123', 'operations': [data, data]}))

# Traceback (most recent call last):
# File "/home/**removed**/protocol/base.py", line 243, in <module>
#    OperationsBatch.parse_obj({'batch_desc': '123', 'operations': [data, data]})
#  File "pydantic/main.py", line 402, in pydantic.main.BaseModel.parse_obj
#  File "pydantic/main.py", line 283, in pydantic.main.BaseModel.__init__
# pydantic.error_wrappers.ValidationError: 2 validation errors for OperationsBatch
# operations -> 0
# value is not a valid dict (type=type_error.dict)
# operations -> 1
# value is not a valid dict (type=type_error.dict)

# Fixed code
def validate(cls: Type["Model"], value: Any) -> "Model":
    if isinstance(value, dict):
        return cls(**value)
    elif isinstance(value, cls):
        return value.copy()
    elif cls.__config__.orm_mode:
        return cls.from_orm(value)
    elif cls.__custom_root_type__:
        return cls.parse_obj(value)
    else:
        try:
            value_as_dict = dict(value)
        except (TypeError, ValueError) as e:
            raise DictError() from e
        return cls(**value_as_dict)
# Buggy code
def __init__(self, default: Any, **kwargs: Any) -> None:
    self.default = default
    self.alias = kwargs.pop("alias", None)
    self.title = kwargs.pop("title", None)
    self.description = kwargs.pop("description", None)
    self.const = kwargs.pop("const", None)
    self.gt = kwargs.pop("gt", None)
    self.ge = kwargs.pop("ge", None)
    self.lt = kwargs.pop("lt", None)
    self.le = kwargs.pop("le", None)
    self.multiple_of = kwargs.pop("multiple_of", None)
    self.min_items = kwargs.pop("min_items", None)
    self.max_items = kwargs.pop("max_items", None)
    self.min_length = kwargs.pop("min_length", None)
    self.max_length = kwargs.pop("max_length", None)
    self.regex = kwargs.pop("regex", None)
    self.extra = kwargs


# Traceback (pydantic.error_wrappers.ValidationError)
MyModel()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<snip>/site-packages/pydantic/main.py", line 274, in __init__
raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for MyModel
myATTRIBUTE
field required (type=value_error.missing)
MyOtherModel()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<snip>/site-packages/pydantic/main.py", line 274, in __init__
raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for MyOtherModel
MY_ATTRIBUTE
field required (type=value_error.missing)

# Fixed code
def __init__(self, default: Any, **kwargs: Any) -> None:
    self.default = default
    self.alias = kwargs.pop("alias", None)
    self.alias_priority = kwargs.pop("alias_priority", 2 if self.alias else None)
    self.title = kwargs.pop("title", None)
    self.description = kwargs.pop("description", None)
    self.const = kwargs.pop("const", None)
    self.gt = kwargs.pop("gt", None)
    self.ge = kwargs.pop("ge", None)
    self.lt = kwargs.pop("lt", None)
    self.le = kwargs.pop("le", None)
    self.multiple_of = kwargs.pop("multiple_of", None)
    self.min_items = kwargs.pop("min_items", None)
    self.max_items = kwargs.pop("max_items", None)
    self.min_length = kwargs.pop("min_length", None)
    self.max_length = kwargs.pop("max_length", None)
    self.regex = kwargs.pop("regex", None)
    self.extra = kwargs
# Buggy code
def set_config(self, config: Type["BaseConfig"]) -> None:
    self.model_config = config
    info_from_config = config.get_field_info(self.name)
    config.prepare_field(self)
    if info_from_config:
        self.field_info.alias = (
            info_from_config.get("alias") or self.field_info.alias or self.name
        )
        self.alias = cast(str, self.field_info.alias)


# Traceback (pydantic.error_wrappers.ValidationError)
MyModel()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<snip>/site-packages/pydantic/main.py", line 274, in __init__
raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for MyModel
myATTRIBUTE
field required (type=value_error.missing)
MyOtherModel()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<snip>/site-packages/pydantic/main.py", line 274, in __init__
raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for MyOtherModel
MY_ATTRIBUTE
field required (type=value_error.missing)

# Fixed code
def set_config(self, config: Type["BaseConfig"]) -> None:
    self.model_config = config
    info_from_config = config.get_field_info(self.name)
    config.prepare_field(self)
    new_alias = info_from_config.get("alias")
    new_alias_priority = info_from_config.get("alias_priority") or 0
    if new_alias and new_alias_priority >= (self.field_info.alias_priority or 0):
        self.field_info.alias = new_alias
        self.field_info.alias_priority = new_alias_priority
        self.alias = new_alias
# Buggy code
def get_field_info(cls, name: str) -> Dict[str, Any]:
    field_info = cls.fields.get(name) or {}
    if isinstance(field_info, str):
        field_info = {"alias": field_info}
    elif cls.alias_generator and "alias" not in field_info:
        alias = cls.alias_generator(name)
        if not isinstance(alias, str):
            raise TypeError(
                f"Config.alias_generator must return str, not {type(alias)}"
            )
        field_info["alias"] = alias
    return field_info


# Traceback (pydantic.error_wrappers.ValidationError)
MyModel()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<snip>/site-packages/pydantic/main.py", line 274, in __init__
raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for MyModel
myATTRIBUTE
field required (type=value_error.missing)
MyOtherModel()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<snip>/site-packages/pydantic/main.py", line 274, in __init__
raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for MyOtherModel
MY_ATTRIBUTE
field required (type=value_error.missing)

# Fixed code
def get_field_info(cls, name: str) -> Dict[str, Any]:
    fields_value = cls.fields.get(name)

    if isinstance(fields_value, str):
        field_info: Dict[str, Any] = {"alias": fields_value}
    elif isinstance(fields_value, dict):
        field_info = fields_value
    else:
        field_info = {}

    if "alias" in field_info:
        field_info.setdefault("alias_priority", 2)

    if field_info.get("alias_priority", 0) <= 1 and cls.alias_generator:
        alias = cls.alias_generator(name)
        if not isinstance(alias, str):
            raise TypeError(
                f"Config.alias_generator must return str, not {type(alias)}"
            )
        field_info.update(alias=alias, alias_priority=1)
    return field_info
# Buggy code
def validate_luhn_check_digit(cls, card_number: str) -> str:
    """
    Based on: https://en.wikipedia.org/wiki/Luhn_algorithm
    """
    sum_ = int(card_number[-1])
    length = len(card_number)
    parity = length % 2
    for i in range(length - 1):
        digit = int(card_number[i])
        if i % 2 == parity:
            digit *= 2
        sum_ += digit
    valid = sum_ % 10 == 0
    if not valid:
        raise errors.LuhnValidationError
    return card_number


# Traceback (pydantic.errors.LuhnValidationError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.7/site-packages/pydantic/types.py", line 657, in validate_luhn_check_digit
raise errors.LuhnValidationError
pydantic.errors.LuhnValidationError: card number is not luhn valid

# Fixed code
def validate_luhn_check_digit(cls, card_number: str) -> str:
    """
    Based on: https://en.wikipedia.org/wiki/Luhn_algorithm
    """
    sum_ = int(card_number[-1])
    length = len(card_number)
    parity = length % 2
    for i in range(length - 1):
        digit = int(card_number[i])
        if i % 2 == parity:
            digit *= 2
        if digit > 9:
            digit -= 9
        sum_ += digit
    valid = sum_ % 10 == 0
    if not valid:
        raise errors.LuhnValidationError
    return card_number
# Buggy code
def validate(cls, value: str) -> str:
    if cls.curtail_length and len(value) > cls.curtail_length:
        value = value[: cls.curtail_length]

    if cls.regex:
        if not cls.regex.match(value):
            raise errors.StrRegexError(pattern=cls.regex.pattern)

    return value


# Traceback (pydantic.error_wrappers.ValidationError)
Traceback (most recent call last):
File "/opt/pycharm-eap/plugins/python/helpers/pydev/pydevd.py", line 1415, in _exec
pydev_imports.execfile(file, globals, locals)  # execute the script
File "/opt/pycharm-eap/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/spalmer1009/.PyCharm2019.3/config/scratches/scratch.py", line 44, in <module>
connection_name=ConnectionName("test"), connection_endpoint=EndpointStr("default"),
File "/home/spalmer1009/.PyCharm2019.3/config/scratches/scratch.py", line 30, in build_from
connection_endpoint=connection_endpoint,
File "pydantic/main.py", line 274, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 2 validation errors for UpRequestEvent
connection_name
Expected unicode, got ConnectionName (type=type_error)
connection_endpoint
Expected unicode, got EndpointStr (type=type_error)

# Fixed code
def validate(cls, value: Union[str]) -> Union[str]:
    if cls.curtail_length and len(value) > cls.curtail_length:
        value = value[: cls.curtail_length]

    if cls.regex:
        if not cls.regex.match(value):
            raise errors.StrRegexError(pattern=cls.regex.pattern)

    return value
# Buggy code
def strict_str_validator(v: Any) -> str:
    if isinstance(v, str):
        return v
    raise errors.StrError()


# Traceback (pydantic.error_wrappers.ValidationError)
Traceback (most recent call last):
File "/opt/pycharm-eap/plugins/python/helpers/pydev/pydevd.py", line 1415, in _exec
pydev_imports.execfile(file, globals, locals)  # execute the script
File "/opt/pycharm-eap/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/spalmer1009/.PyCharm2019.3/config/scratches/scratch.py", line 44, in <module>
connection_name=ConnectionName("test"), connection_endpoint=EndpointStr("default"),
File "/home/spalmer1009/.PyCharm2019.3/config/scratches/scratch.py", line 30, in build_from
connection_endpoint=connection_endpoint,
File "pydantic/main.py", line 274, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 2 validation errors for UpRequestEvent
connection_name
Expected unicode, got ConnectionName (type=type_error)
connection_endpoint
Expected unicode, got EndpointStr (type=type_error)

# Fixed code
def strict_str_validator(v: Any) -> Union[str]:
    if isinstance(v, str):
        return v
    raise errors.StrError()
# Buggy code
def display_as_type(v: AnyType) -> str:
    if not isinstance(v, typing_base) and not isinstance(v, type):
        v = type(v)

    if lenient_issubclass(v, Enum):
        if issubclass(v, int):
            return "int"
        elif issubclass(v, str):
            return "str"
        else:
            return "enum"

    try:
        return v.__name__
    except AttributeError:
        # happens with unions
        return str(v)


# Traceback (pydantic.error_wrappers.ValidationError)
from pydantic import BaseModel, urlstr
class DatabaseConfig(BaseModel):
...     url: urlstr(schemes={'postgresql'}, require_tld=False) = ...
...
DatabaseConfig(url='postgresql://diary_test@localhost/diary_test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pydantic/main.py", line 235, in __init__
object.__setattr__(self, '__values__', self._process_values(data))
File "pydantic/main.py", line 438, in _process_values
return validate_model(self, input_data)  # type: ignore
File "pydantic/main.py", line 635, in validate_model
raise ValidationError(errors)
pydantic.error_wrappers.ValidationError: 1 validation error
url
url string does not match regex (type=value_error.url.regex)

# Fixed code
def display_as_type(v: AnyType) -> str:
    if not isinstance(v, typing_base) and not isinstance(v, type):
        v = type(v)

    if isinstance(v, type) and issubclass(v, Enum):
        if issubclass(v, int):
            return "int"
        elif issubclass(v, str):
            return "str"
        else:
            return "enum"

    try:
        return v.__name__
    except AttributeError:
        # happens with unions
        return str(v)
# Buggy code
def setattr_validate_assignment(self: "DataclassType", name: str, value: Any) -> None:
    if self.__initialised__:
        d = dict(self.__dict__)
        d.pop(name)
        value, error_ = self.__pydantic_model__.__fields__[name].validate(
            value, d, loc=name, cls=self.__class__
        )
        if error_:
            raise ValidationError([error_], type(self))

    object.__setattr__(self, name, value)


# Traceback (pydantic.ValidationError)
import contextlib
import datetime
import pydantic


class ModelWithoutValidation(pydantic.BaseModel):
name: str = None
birthdate: datetime.date = None

class Config:
extra = pydantic.Extra.allow
validate_assignment = False  # <<< !!!


obj = ModelWithoutValidation(name="Jim Smith")
obj.name = "John Doe"  # OK: Does not fail because assignment is not validated
obj.birthdate = "1983-16-72"  # OK: Does not fail because assignment is not validated
obj.fake_stuff = "asdf"  # OK: Can assign new field


class ModelWithValidation(pydantic.BaseModel):
name: str = None
birthdate: datetime.date = None

class Config:
extra = pydantic.Extra.allow
validate_assignment = True  # <<< !!!


obj = ModelWithValidation(name="Jim Smith")
obj.name = "John Doe"  # OK: Does not fail because the value is acceptable
with contextlib.suppress(pydantic.ValidationError):
obj.birthdate = "1983-16-72"  # OK: Fails because the value is wrong
obj.fake_stuff = "asdf"
# FAIL: Cannot assign new field becaue there's no valiator
# Traceback (most recent call last):
#   File "/home/yaraslau/Projects/Dialogue/tmp/test.py", line 34, in <module>
#     obj.fake_stuff = "asdf"
#   File "pydantic/main.py", line 294, in pydantic.main.BaseModel.__setattr__
# KeyError: 'fake_stuff'

# Fixed code
def setattr_validate_assignment(self: "DataclassType", name: str, value: Any) -> None:
    if self.__initialised__:
        d = dict(self.__dict__)
        d.pop(name, None)
        known_field = self.__pydantic_model__.__fields__.get(name, None)
        if known_field:
            value, error_ = known_field.validate(value, d, loc=name, cls=self.__class__)
            if error_:
                raise ValidationError([error_], type(self))

    object.__setattr__(self, name, value)
# Buggy code
def __setattr__(self, name, value):
    if self.__config__.extra is not Extra.allow and name not in self.__fields__:
        raise ValueError(f'"{self.__class__.__name__}" object has no field "{name}"')
    elif not self.__config__.allow_mutation:
        raise TypeError(
            f'"{self.__class__.__name__}" is immutable and does not support item assignment'
        )
    elif self.__config__.validate_assignment:
        value_, error_ = self.fields[name].validate(
            value, self.dict(exclude={name}), loc=name
        )
        if error_:
            raise ValidationError([error_], type(self))
        else:
            self.__dict__[name] = value_
            self.__fields_set__.add(name)
    else:
        self.__dict__[name] = value
        self.__fields_set__.add(name)


# Traceback (pydantic.ValidationError)
import contextlib
import datetime
import pydantic


class ModelWithoutValidation(pydantic.BaseModel):
name: str = None
birthdate: datetime.date = None

class Config:
extra = pydantic.Extra.allow
validate_assignment = False  # <<< !!!


obj = ModelWithoutValidation(name="Jim Smith")
obj.name = "John Doe"  # OK: Does not fail because assignment is not validated
obj.birthdate = "1983-16-72"  # OK: Does not fail because assignment is not validated
obj.fake_stuff = "asdf"  # OK: Can assign new field


class ModelWithValidation(pydantic.BaseModel):
name: str = None
birthdate: datetime.date = None

class Config:
extra = pydantic.Extra.allow
validate_assignment = True  # <<< !!!


obj = ModelWithValidation(name="Jim Smith")
obj.name = "John Doe"  # OK: Does not fail because the value is acceptable
with contextlib.suppress(pydantic.ValidationError):
obj.birthdate = "1983-16-72"  # OK: Fails because the value is wrong
obj.fake_stuff = "asdf"
# FAIL: Cannot assign new field becaue there's no valiator
# Traceback (most recent call last):
#   File "/home/yaraslau/Projects/Dialogue/tmp/test.py", line 34, in <module>
#     obj.fake_stuff = "asdf"
#   File "pydantic/main.py", line 294, in pydantic.main.BaseModel.__setattr__
# KeyError: 'fake_stuff'

# Fixed code
def __setattr__(self, name, value):
    if self.__config__.extra is not Extra.allow and name not in self.__fields__:
        raise ValueError(f'"{self.__class__.__name__}" object has no field "{name}"')
    elif not self.__config__.allow_mutation:
        raise TypeError(
            f'"{self.__class__.__name__}" is immutable and does not support item assignment'
        )
    elif self.__config__.validate_assignment:
        known_field = self.fields.get(name, None)
        if known_field:
            value, error_ = known_field.validate(
                value, self.dict(exclude={name}), loc=name
            )
            if error_:
                raise ValidationError([error_], type(self))
    self.__dict__[name] = value
    self.__fields_set__.add(name)
# Buggy code
def __str__(self) -> str:
    permitted = ", ".join(repr(v.value) for v in self.ctx["enum_type"])  # type: ignore
    return f"value is not a valid enumeration member; permitted: {permitted}"


# Traceback (pydantic.error_wrappers.ValidationError)
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/Users/josepcugat/.pyenv/versions/current/lib/python3.6/site-packages/pydantic/main.py", line 276, in __init__
values, fields_set, _ = validate_model(__pydantic_self__, data)
File "/Users/josepcugat/.pyenv/versions/current/lib/python3.6/site-packages/pydantic/main.py", line 790, in validate_model
raise ValidationError(errors)
pydantic.error_wrappers.ValidationError: 1 validation error
bar
value is not a valid enumeration member; permitted: 'VALID' (type=type_error.enum; enum_type=<enum 'MyEnum'>)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "/Users/josepcugat/.pyenv/versions/current/lib/python3.6/site-packages/pydantic/error_wrappers.py", line 62, in json
return json.dumps(self.errors(), indent=indent)
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/encoder.py", line 201, in encode
chunks = list(chunks)
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/encoder.py", line 428, in _iterencode
yield from _iterencode_list(o, _current_indent_level)
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/encoder.py", line 325, in _iterencode_list
yield from chunks
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/encoder.py", line 404, in _iterencode_dict
yield from chunks
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/encoder.py", line 404, in _iterencode_dict
yield from chunks
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/encoder.py", line 437, in _iterencode
o = _default(o)
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'EnumMeta' is not JSON serializable

# Fixed code
def __str__(self) -> str:
    permitted = ", ".join(repr(v.value) for v in self.ctx["enum_values"])  # type: ignore
    return f"value is not a valid enumeration member; permitted: {permitted}"
# Buggy code
def enum_validator(v: Any, field: "Field", config: "BaseConfig") -> Enum:
    try:
        enum_v = field.type_(v)
    except ValueError:
        raise errors.EnumError(enum_type=field.type_)
    return enum_v.value if config.use_enum_values else enum_v


# Traceback (pydantic.error_wrappers.ValidationError)
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/Users/josepcugat/.pyenv/versions/current/lib/python3.6/site-packages/pydantic/main.py", line 276, in __init__
values, fields_set, _ = validate_model(__pydantic_self__, data)
File "/Users/josepcugat/.pyenv/versions/current/lib/python3.6/site-packages/pydantic/main.py", line 790, in validate_model
raise ValidationError(errors)
pydantic.error_wrappers.ValidationError: 1 validation error
bar
value is not a valid enumeration member; permitted: 'VALID' (type=type_error.enum; enum_type=<enum 'MyEnum'>)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "/Users/josepcugat/.pyenv/versions/current/lib/python3.6/site-packages/pydantic/error_wrappers.py", line 62, in json
return json.dumps(self.errors(), indent=indent)
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/encoder.py", line 201, in encode
chunks = list(chunks)
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/encoder.py", line 428, in _iterencode
yield from _iterencode_list(o, _current_indent_level)
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/encoder.py", line 325, in _iterencode_list
yield from chunks
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/encoder.py", line 404, in _iterencode_dict
yield from chunks
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/encoder.py", line 404, in _iterencode_dict
yield from chunks
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/encoder.py", line 437, in _iterencode
o = _default(o)
File "/Users/josepcugat/.pyenv/versions/3.6.8/lib/python3.6/json/encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'EnumMeta' is not JSON serializable

# Fixed code
def enum_validator(v: Any, field: "Field", config: "BaseConfig") -> Enum:
    try:
        enum_v = field.type_(v)
    except ValueError:
        # field.type_ should be an enum, so will be iterable
        raise errors.EnumError(enum_values=list(field.type_))  # type: ignore
    return enum_v.value if config.use_enum_values else enum_v
# Buggy code
def truncate(v: Union[str], *, max_len: int = 80) -> str:
    """
    Truncate a value and add a unicode ellipsis (three dots) to the end if it was too long
    """
    if isinstance(v, str) and len(v) > (max_len - 2):
        # -3 so quote + string + … + quote has correct length
        return (v[: (max_len - 3)] + "…").__repr__()
    v = v.__repr__()
    if len(v) > max_len:
        v = v[: max_len - 1] + "…"
    return v


# Traceback (TypeError)
Traceback (most recent call last):
File "test.py", line 23, in <module>
print(TestSettings(cls=TestClass))
File "pydantic/main.py", line 534, in pydantic.main.BaseModel.__str__
File "pydantic/main.py", line 530, in genexpr
File "pydantic/main.py", line 530, in genexpr
File "pydantic/utils.py", line 158, in pydantic.utils.truncate
TypeError: descriptor '__repr__' of 'object' object needs an argument

# Fixed code
def truncate(v: Union[str], *, max_len: int = 80) -> str:
    """
    Truncate a value and add a unicode ellipsis (three dots) to the end if it was too long
    """
    if isinstance(v, str) and len(v) > (max_len - 2):
        # -3 so quote + string + … + quote has correct length
        return (v[: (max_len - 3)] + "…").__repr__()
    try:
        v = v.__repr__()
    except TypeError:
        v = type(v).__repr__(v)  # in case v is a type
    if len(v) > max_len:
        v = v[: max_len - 1] + "…"
    return v
# Buggy code
def _pydantic_post_init(self: "DataclassType", *initvars: Any) -> None:
    if self.__post_init_original__:
        self.__post_init_original__(*initvars)
    d = validate_model(self.__pydantic_model__, self.__dict__, cls=self.__class__)[0]
    object.__setattr__(self, "__dict__", d)
    object.__setattr__(self, "__initialised__", True)
    if self.__post_init_post_parse__:
        self.__post_init_post_parse__()


# Traceback (RecursionError)
---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
<ipython-input-28-55581d931e2a> in <module>
----> 1 B(b=1, a=2)

<string> in __init__(self, a, b)

[path_removed]/.venv/lib/python3.7/site-packages/pydantic/dataclasses.py in _pydantic_post_init(self)
30     object.__setattr__(self, '__initialised__', True)
31     if self.__post_init_original__:
---> 32         self.__post_init_original__()
33
34

<ipython-input-27-252024563a0b> in __post_init__(self)
11
12     def __post_init__(self):
---> 13         super().__post_init__()
14         print("B")

... last 2 frames repeated, from the frame below ...

[path_removed]/.venv/lib/python3.7/site-packages/pydantic/dataclasses.py in _pydantic_post_init(self)
30     object.__setattr__(self, '__initialised__', True)
31     if self.__post_init_original__:
---> 32         self.__post_init_original__()
33
34

RecursionError: maximum recursion depth exceeded while calling a Python object

# Fixed code
def _pydantic_post_init(self: "DataclassType", *initvars: Any) -> None:
    if post_init_original is not None:
        post_init_original(self, *initvars)
    d = validate_model(self.__pydantic_model__, self.__dict__, cls=self.__class__)[0]
    object.__setattr__(self, "__dict__", d)
    object.__setattr__(self, "__initialised__", True)
    if post_init_post_parse is not None:
        post_init_post_parse(self)
# Buggy code
def _get_key_factory(self, by_alias: bool) -> Callable[..., str]:
    if by_alias:
        return lambda fields, key: fields[key].alias

    return lambda _, key: key


# Traceback (KeyError)
Traceback (most recent call last):
File "...", line 41, in ...
print(m.dict(by_alias=True))  # error
File ".../python3.7/site-packages/pydantic/main.py", line 282, in dict
get_key(k): v for k, v in self._iter(by_alias=by_alias, skip_defaults=skip_defaults)
File ".../python3.7/site-packages/pydantic/main.py", line 282, in <dictcomp>
get_key(k): v for k, v in self._iter(by_alias=by_alias, skip_defaults=skip_defaults)
File ".../python3.7/site-packages/pydantic/main.py", line 293, in <lambda>
return lambda fields, key: fields[key].alias
KeyError: 'extra_column'

# Fixed code
def _get_key_factory(self, by_alias: bool) -> Callable[..., str]:
    if by_alias:
        return lambda fields, key: fields[key].alias if key in fields else key

    return lambda _, key: key
# Buggy code
def include_in_schema(self) -> bool:
    """
    False if this is a simple field just allowing None as used in Unions/Optional.
    """
    return len(self.validators) != 1 or self.validators[0][1] != is_none_validator


# Traceback (ValueError)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/.../lib/python3.6/site-packages/pydantic/main.py", line 292, in schema
s = model_schema(cls, by_alias=by_alias)
File "/Users/.../lib/python3.6/site-packages/pydantic/schema.py", line 193, in model_schema
model, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix
File "/Users/.../lib/python3.6/site-packages/pydantic/schema.py", line 463, in model_process_schema
model, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix
File "/Users/.../lib/python3.6/site-packages/pydantic/schema.py", line 484, in model_type_schema
f, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix
File "/Users/.../lib/python3.6/site-packages/pydantic/schema.py", line 240, in field_schema
ref_prefix=ref_prefix,
File "/Users/.../lib/python3.6/site-packages/pydantic/schema.py", line 442, in field_type_schema
ref_prefix=ref_prefix,
File "/Users/.../lib/python3.6/site-packages/pydantic/schema.py", line 610, in field_singleton_schema
ref_prefix=ref_prefix,
File "/Users/.../lib/python3.6/site-packages/pydantic/schema.py", line 534, in field_singleton_sub_fields_schema
ref_prefix=ref_prefix,
File "/Users/.../lib/python3.6/site-packages/pydantic/schema.py", line 442, in field_type_schema
ref_prefix=ref_prefix,
File "/Users/.../lib/python3.6/site-packages/pydantic/schema.py", line 645, in field_singleton_schema
raise ValueError(f'Value not declarable with JSON Schema, field: {field}')
ValueError: Value not declarable with JSON Schema, field: field_NoneType type=NoneType required

# Fixed code
def include_in_schema(self) -> bool:
    """
    False if this is a simple field just allowing None as used in Unions/Optional.
    """
    return self.type_ != NoneType