from dataclasses import dataclass
def validate_str(max_length):
def _validate(f):
def wrapper(self, value):
if type(value) is not str:
raise TypeError(f"Expected str, got: {type(value)}")
elif len(value) > max_length:
raise ValueError(f"Expected string of max length {max_length}, got string of length {len(value)} : {value}")
f(self, value)
return wrapper
return _validate
@dataclass
class Person:
name: str
@validate_str(10)
def address(self, value):
self.address = value
class Student:
def __init__(self, nume, nota):
self.nume = nume
self.nota = nota
def __gt__(self, other):
return self.nota > other.nota
Apoi puteți compara doi studenți folosind >:
s1 = Student("Ana", 9)
s2 = Student("Bogdan", 8)
print(s1 > s2) # True
În acest caz, s1.__gt__(s2) este echivalent cu s1 > s2.
Dar nu puteți folosi __gt__() pentru a compara lungimea unei valori cu o valoare maximă,
deoarece acestea nu sunt obiecte personalizate care au definit __gt__().
În schimb, trebuie să folosiți operatorul > direct.
How to make a field required in a Python dataclass, similar to the required
option in a Mongoose schema. One way to make a field required in a Python dataclass is to use the field
function from the dataclasses
module and set the default
or default_factory
arguments to dataclasses.MISSING
. This will raise a TypeError
if the field is not provided when creating an instance of the class. For example:
from dataclasses import dataclass, field, MISSING
@dataclass
class Person:
name: str = field(default=MISSING) # name is required
age: int = 0 # age has a default value of 0
hobbies: list[str] = field(default_factory=list) # hobbies is an empty list by default
p1 = Person(name="Alice", age=25, hobbies=["reading", "writing"]) # valid
p2 = Person(name="Bob") # valid, age and hobbies are set to default values
p3 = Person(age=30, hobbies=["gaming", "coding"]) # invalid, name is missing
Another way to make a field required in a Python dataclass is to use a validator function that checks if the field is None
or has some other invalid value, and raise an exception if so. You can
write your own validator function, or use a library like pydantic
or attrs
that provides validation features. For example, using pydantic
:
from pydantic.dataclasses import dataclass
@dataclass
class Person:
name: str # name is required, pydantic will raise a ValidationError if it is missing or not a string
age: int = 0 # age has a default value of 0
hobbies: list[str] = None # hobbies is optional, but must be a list of strings if provided
p1 = Person(name="Alice", age=25, hobbies=["reading", "writing"]) # valid
p2 = Person(name="Bob") # valid, age is set to default value and hobbies is None
p3 = Person(age=30, hobbies=["gaming", "coding"]) # invalid, name is missing
p4 = Person(name="Charlie", age="twenty", hobbies=42) # invalid, age and hobbies have wrong types