hdmf-common¶
1.5.0¶
- class datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])¶
The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.
- hour¶
- minute¶
- second¶
- microsecond¶
- tzinfo¶
- fold¶
- fromtimestamp()¶
timestamp[, tz] -> tz’s local time from POSIX timestamp.
- utcfromtimestamp()¶
Construct a naive UTC datetime from a POSIX timestamp.
- now()¶
Returns new datetime object representing current time local to tz.
- tz
Timezone object.
If no tz is specified, uses local timezone.
- utcnow()¶
Return a new datetime representing UTC day and time.
- combine()¶
date, time -> datetime with same date and time fields
- fromisoformat()¶
string -> datetime from a string in most ISO 8601 formats
- timetuple()¶
Return time tuple, compatible with time.localtime().
- timestamp()¶
Return POSIX timestamp as float.
- utctimetuple()¶
Return UTC time tuple, compatible with time.localtime().
- date()¶
Return date object with same year, month and day.
- time()¶
Return time object with same time but with tzinfo=None.
- timetz()¶
Return time object with same time and tzinfo.
- replace()¶
Return datetime with new specified fields.
- astimezone()¶
tz -> convert to local time in new timezone tz
- ctime()¶
Return ctime() style string.
- isoformat()¶
[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. sep is used to separate the year from the time, and defaults to ‘T’. The optional argument timespec specifies the number of additional terms of the time to include. Valid options are ‘auto’, ‘hours’, ‘minutes’, ‘seconds’, ‘milliseconds’ and ‘microseconds’.
- strptime()¶
string, format -> new datetime parsed from a string (like time.strptime()).
- utcoffset()¶
Return self.tzinfo.utcoffset(self).
- tzname()¶
Return self.tzinfo.tzname(self).
- dst()¶
Return self.tzinfo.dst(self).
- max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)¶
- min = datetime.datetime(1, 1, 1, 0, 0)¶
- resolution = datetime.timedelta(microseconds=1)¶
- class date¶
date(year, month, day) –> date object
- fromtimestamp()¶
Create a date from a POSIX timestamp.
The timestamp is a number, e.g. created via time.time(), that is interpreted as local time.
- today()¶
Current date or datetime: same as self.__class__.fromtimestamp(time.time()).
- fromordinal()¶
int -> date corresponding to a proleptic Gregorian ordinal.
- fromisoformat()¶
str -> Construct a date from a string in ISO 8601 format.
- fromisocalendar()¶
int, int, int -> Construct a date from the ISO year, week number and weekday.
This is the inverse of the date.isocalendar() function
- ctime()¶
Return ctime() style string.
- strftime()¶
format -> strftime() style string.
- isoformat()¶
Return string in ISO 8601 format, YYYY-MM-DD.
- year¶
- month¶
- day¶
- timetuple()¶
Return time tuple, compatible with time.localtime().
- toordinal()¶
Return proleptic Gregorian ordinal. January 1 of year 1 is day 1.
- replace()¶
Return date with new specified fields.
- weekday()¶
Return the day of the week represented by the date. Monday == 0 … Sunday == 6
- isoweekday()¶
Return the day of the week represented by the date. Monday == 1 … Sunday == 7
- isocalendar()¶
Return a named tuple containing ISO year, week number, and weekday.
- max = datetime.date(9999, 12, 31)¶
- min = datetime.date(1, 1, 1)¶
- resolution = datetime.timedelta(days=1)¶
- class Decimal(value='0', context=None)¶
Construct a new Decimal object. ‘value’ can be an integer, string, tuple, or another Decimal object. If no value is given, return Decimal(‘0’). The context does not affect the conversion and is only passed to determine if the InvalidOperation trap is active.
- adjusted()¶
Return the adjusted exponent of the number. Defined as exp + digits - 1.
- as_integer_ratio()¶
Return a pair of integers, whose ratio is exactly equal to the original Decimal and with a positive denominator. The ratio is in lowest terms. Raise OverflowError on infinities and a ValueError on NaNs.
- as_tuple()¶
Return a tuple representation of the number.
- canonical()¶
Return the canonical encoding of the argument. Currently, the encoding of a Decimal instance is always canonical, so this operation returns its argument unchanged.
- compare(other, context=None)¶
Compare self to other. Return a decimal value:
a or b is a NaN ==> Decimal(‘NaN’) a < b ==> Decimal(‘-1’) a == b ==> Decimal(‘0’) a > b ==> Decimal(‘1’)
- compare_signal(other, context=None)¶
Identical to compare, except that all NaNs signal.
- compare_total(other, context=None)¶
Compare two operands using their abstract representation rather than their numerical value. Similar to the compare() method, but the result gives a total ordering on Decimal instances. Two Decimal instances with the same numeric value but different representations compare unequal in this ordering:
>>> Decimal('12.0').compare_total(Decimal('12')) Decimal('-1')
Quiet and signaling NaNs are also included in the total ordering. The result of this function is Decimal(‘0’) if both operands have the same representation, Decimal(‘-1’) if the first operand is lower in the total order than the second, and Decimal(‘1’) if the first operand is higher in the total order than the second operand. See the specification for details of the total order.
This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.
- compare_total_mag(other, context=None)¶
Compare two operands using their abstract representation rather than their value as in compare_total(), but ignoring the sign of each operand.
x.compare_total_mag(y) is equivalent to x.copy_abs().compare_total(y.copy_abs()).
This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.
- conjugate()¶
Return self.
- copy_abs()¶
Return the absolute value of the argument. This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed.
- copy_negate()¶
Return the negation of the argument. This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed.
- copy_sign(other, context=None)¶
Return a copy of the first operand with the sign set to be the same as the sign of the second operand. For example:
>>> Decimal('2.3').copy_sign(Decimal('-1.5')) Decimal('-2.3')
This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.
- exp(context=None)¶
Return the value of the (natural) exponential function e**x at the given number. The function always uses the ROUND_HALF_EVEN mode and the result is correctly rounded.
- fma(other, third, context=None)¶
Fused multiply-add. Return self*other+third with no rounding of the intermediate product self*other.
>>> Decimal(2).fma(3, 5) Decimal('11')
- from_float()¶
Class method that converts a float to a decimal number, exactly. Since 0.1 is not exactly representable in binary floating point, Decimal.from_float(0.1) is not the same as Decimal(‘0.1’).
>>> Decimal.from_float(0.1) Decimal('0.1000000000000000055511151231257827021181583404541015625') >>> Decimal.from_float(float('nan')) Decimal('NaN') >>> Decimal.from_float(float('inf')) Decimal('Infinity') >>> Decimal.from_float(float('-inf')) Decimal('-Infinity')
- imag¶
- is_canonical()¶
Return True if the argument is canonical and False otherwise. Currently, a Decimal instance is always canonical, so this operation always returns True.
- is_finite()¶
Return True if the argument is a finite number, and False if the argument is infinite or a NaN.
- is_infinite()¶
Return True if the argument is either positive or negative infinity and False otherwise.
- is_nan()¶
Return True if the argument is a (quiet or signaling) NaN and False otherwise.
- is_normal(context=None)¶
Return True if the argument is a normal finite non-zero number with an adjusted exponent greater than or equal to Emin. Return False if the argument is zero, subnormal, infinite or a NaN.
- is_qnan()¶
Return True if the argument is a quiet NaN, and False otherwise.
- is_signed()¶
Return True if the argument has a negative sign and False otherwise. Note that both zeros and NaNs can carry signs.
- is_snan()¶
Return True if the argument is a signaling NaN and False otherwise.
- is_subnormal(context=None)¶
Return True if the argument is subnormal, and False otherwise. A number is subnormal if it is non-zero, finite, and has an adjusted exponent less than Emin.
- is_zero()¶
Return True if the argument is a (positive or negative) zero and False otherwise.
- ln(context=None)¶
Return the natural (base e) logarithm of the operand. The function always uses the ROUND_HALF_EVEN mode and the result is correctly rounded.
- log10(context=None)¶
Return the base ten logarithm of the operand. The function always uses the ROUND_HALF_EVEN mode and the result is correctly rounded.
- logb(context=None)¶
For a non-zero number, return the adjusted exponent of the operand as a Decimal instance. If the operand is a zero, then Decimal(‘-Infinity’) is returned and the DivisionByZero condition is raised. If the operand is an infinity then Decimal(‘Infinity’) is returned.
- logical_and(other, context=None)¶
Return the digit-wise ‘and’ of the two (logical) operands.
- logical_invert(context=None)¶
Return the digit-wise inversion of the (logical) operand.
- logical_or(other, context=None)¶
Return the digit-wise ‘or’ of the two (logical) operands.
- logical_xor(other, context=None)¶
Return the digit-wise ‘exclusive or’ of the two (logical) operands.
- max(other, context=None)¶
Maximum of self and other. If one operand is a quiet NaN and the other is numeric, the numeric operand is returned.
- max_mag(other, context=None)¶
Similar to the max() method, but the comparison is done using the absolute values of the operands.
- min(other, context=None)¶
Minimum of self and other. If one operand is a quiet NaN and the other is numeric, the numeric operand is returned.
- min_mag(other, context=None)¶
Similar to the min() method, but the comparison is done using the absolute values of the operands.
- next_minus(context=None)¶
Return the largest number representable in the given context (or in the current default context if no context is given) that is smaller than the given operand.
- next_plus(context=None)¶
Return the smallest number representable in the given context (or in the current default context if no context is given) that is larger than the given operand.
- next_toward(other, context=None)¶
If the two operands are unequal, return the number closest to the first operand in the direction of the second operand. If both operands are numerically equal, return a copy of the first operand with the sign set to be the same as the sign of the second operand.
- normalize(context=None)¶
Normalize the number by stripping the rightmost trailing zeros and converting any result equal to Decimal(‘0’) to Decimal(‘0e0’). Used for producing canonical values for members of an equivalence class. For example, Decimal(‘32.100’) and Decimal(‘0.321000e+2’) both normalize to the equivalent value Decimal(‘32.1’).
- number_class(context=None)¶
Return a string describing the class of the operand. The returned value is one of the following ten strings:
‘-Infinity’, indicating that the operand is negative infinity.
‘-Normal’, indicating that the operand is a negative normal number.
‘-Subnormal’, indicating that the operand is negative and subnormal.
‘-Zero’, indicating that the operand is a negative zero.
‘+Zero’, indicating that the operand is a positive zero.
‘+Subnormal’, indicating that the operand is positive and subnormal.
‘+Normal’, indicating that the operand is a positive normal number.
‘+Infinity’, indicating that the operand is positive infinity.
‘NaN’, indicating that the operand is a quiet NaN (Not a Number).
‘sNaN’, indicating that the operand is a signaling NaN.
- quantize(exp, rounding=None, context=None)¶
Return a value equal to the first operand after rounding and having the exponent of the second operand.
>>> Decimal('1.41421356').quantize(Decimal('1.000')) Decimal('1.414')
Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision, then an InvalidOperation is signaled. This guarantees that, unless there is an error condition, the quantized exponent is always equal to that of the right-hand operand.
Also unlike other operations, quantize never signals Underflow, even if the result is subnormal and inexact.
If the exponent of the second operand is larger than that of the first, then rounding may be necessary. In this case, the rounding mode is determined by the rounding argument if given, else by the given context argument; if neither argument is given, the rounding mode of the current thread’s context is used.
- radix()¶
Return Decimal(10), the radix (base) in which the Decimal class does all its arithmetic. Included for compatibility with the specification.
- real¶
- remainder_near(other, context=None)¶
Return the remainder from dividing self by other. This differs from self % other in that the sign of the remainder is chosen so as to minimize its absolute value. More precisely, the return value is self - n * other where n is the integer nearest to the exact value of self / other, and if two integers are equally near then the even one is chosen.
If the result is zero then its sign will be the sign of self.
- rotate(other, context=None)¶
Return the result of rotating the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to rotate. If the second operand is positive then rotation is to the left; otherwise rotation is to the right. The coefficient of the first operand is padded on the left with zeros to length precision if necessary. The sign and exponent of the first operand are unchanged.
- same_quantum(other, context=None)¶
Test whether self and other have the same exponent or whether both are NaN.
This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.
- scaleb(other, context=None)¶
Return the first operand with the exponent adjusted the second. Equivalently, return the first operand multiplied by 10**other. The second operand must be an integer.
- shift(other, context=None)¶
Return the result of shifting the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to shift. If the second operand is positive, then the shift is to the left; otherwise the shift is to the right. Digits shifted into the coefficient are zeros. The sign and exponent of the first operand are unchanged.
- sqrt(context=None)¶
Return the square root of the argument to full precision. The result is correctly rounded using the ROUND_HALF_EVEN rounding mode.
- to_eng_string(context=None)¶
Convert to an engineering-type string. Engineering notation has an exponent which is a multiple of 3, so there are up to 3 digits left of the decimal place. For example, Decimal(‘123E+1’) is converted to Decimal(‘1.23E+3’).
The value of context.capitals determines whether the exponent sign is lower or upper case. Otherwise, the context does not affect the operation.
- to_integral(rounding=None, context=None)¶
Identical to the to_integral_value() method. The to_integral() name has been kept for compatibility with older versions.
- to_integral_exact(rounding=None, context=None)¶
Round to the nearest integer, signaling Inexact or Rounded as appropriate if rounding occurs. The rounding mode is determined by the rounding parameter if given, else by the given context. If neither parameter is given, then the rounding mode of the current default context is used.
- to_integral_value(rounding=None, context=None)¶
Round to the nearest integer without signaling Inexact or Rounded. The rounding mode is determined by the rounding parameter if given, else by the given context. If neither parameter is given, then the rounding mode of the current default context is used.
- class Enum(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
Create a collection of name/value pairs.
Example enumeration:
>>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3
Access them by:
attribute access:
>>> Color.RED <Color.RED: 1>
value lookup:
>>> Color(1) <Color.RED: 1>
name lookup:
>>> Color['RED'] <Color.RED: 1>
Enumerations can be iterated over, and know how many members they have:
>>> len(Color) 3
>>> list(Color) [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.
- class Any(*args, **kwargs)¶
Special type indicating an unconstrained type.
Any is compatible with every type.
Any assumed to have all methods.
All values assumed to be instances of Any.
Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.
- class BaseModel(**data: Any)¶
Usage docs: https://docs.pydantic.dev/2.8/concepts/models/
A base class for creating Pydantic models.
- __class_vars__¶
The names of classvars defined on the model.
- __private_attributes__¶
Metadata about the private attributes of the model.
- __signature__¶
The signature for instantiating the model.
- __pydantic_complete__¶
Whether model building is completed, or if there are still undefined fields.
- __pydantic_core_schema__¶
The pydantic-core schema used to build the SchemaValidator and SchemaSerializer.
- __pydantic_custom_init__¶
Whether the model has a custom __init__ function.
- __pydantic_decorators__¶
Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.
- __pydantic_generic_metadata__¶
Metadata for generic models; contains data used for a similar purpose to __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.
- __pydantic_parent_namespace__¶
Parent namespace of the model, used for automatic rebuilding of models.
- __pydantic_post_init__¶
The name of the post-init method for the model, if defined.
- __pydantic_root_model__¶
Whether the model is a RootModel.
- __pydantic_serializer__¶
The pydantic-core SchemaSerializer used to dump instances of the model.
- __pydantic_validator__¶
The pydantic-core SchemaValidator used to validate instances of the model.
- __pydantic_extra__¶
An instance attribute with the values of extra fields from validation when model_config[‘extra’] == ‘allow’.
- __pydantic_fields_set__¶
An instance attribute with the names of fields explicitly set.
- __pydantic_private__¶
Instance attribute with the values of private attributes set on the model instance.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- model_fields: ClassVar[dict[str, FieldInfo]] = {}¶
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}¶
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- property model_extra: dict[str, Any] | None¶
Get extra fields set during validation.
- Returns:
A dictionary of extra fields, or None if config.extra is not set to “allow”.
- property model_fields_set: set[str]¶
Returns the set of fields that have been explicitly set on this model instance.
- Returns:
- A set of strings representing the fields that have been set,
i.e. that were not filled from defaults.
- classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self¶
Creates a new instance of the Model class with validated data.
Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.
- !!! note
model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.
- Parameters:
_fields_set – The set of field names accepted for the Model instance.
values – Trusted or pre-validated data dictionary.
- Returns:
A new instance of the Model class with validated data.
- model_copy(*, update: dict[str, Any] | None = None, deep: bool = False) Self¶
Usage docs: https://docs.pydantic.dev/2.8/concepts/serialization/#model_copy
Returns a copy of the model.
- Parameters:
update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
deep – Set to True to make a deep copy of the model.
- Returns:
New model instance.
- model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: Set[int] | Set[str] | Dict[int, Any] | Dict[str, Any] | None = None, exclude: Set[int] | Set[str] | Dict[int, Any] | Dict[str, Any] | None = None, context: Any | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, serialize_as_any: bool = False) dict[str, Any]¶
Usage docs: https://docs.pydantic.dev/2.8/concepts/serialization/#modelmodel_dump
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
- Parameters:
mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.
include – A set of fields to include in the output.
exclude – A set of fields to exclude from the output.
context – Additional context to pass to the serializer.
by_alias – Whether to use the field’s alias in the dictionary key if defined.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
- Returns:
A dictionary representation of the model.
- model_dump_json(*, indent: int | None = None, include: Set[int] | Set[str] | Dict[int, Any] | Dict[str, Any] | None = None, exclude: Set[int] | Set[str] | Dict[int, Any] | Dict[str, Any] | None = None, context: Any | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, serialize_as_any: bool = False) str¶
Usage docs: https://docs.pydantic.dev/2.8/concepts/serialization/#modelmodel_dump_json
Generates a JSON representation of the model using Pydantic’s to_json method.
- Parameters:
indent – Indentation to use in the JSON output. If None is passed, the output will be compact.
include – Field(s) to include in the JSON output.
exclude – Field(s) to exclude from the JSON output.
context – Additional context to pass to the serializer.
by_alias – Whether to serialize using field aliases.
exclude_unset – Whether to exclude fields that have not been explicitly set.
exclude_defaults – Whether to exclude fields that are set to their default value.
exclude_none – Whether to exclude fields that have a value of None.
round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.
- Returns:
A JSON string representation of the model.
- classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[~pydantic.json_schema.GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: ~typing.Literal['validation', 'serialization'] = 'validation') dict[str, Any]¶
Generates a JSON schema for a model class.
- Parameters:
by_alias – Whether to use attribute aliases or not.
ref_template – The reference template.
schema_generator – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications
mode – The mode in which to generate the schema.
- Returns:
The JSON schema for the given model class.
- classmethod model_parametrized_name(params: tuple[type[Any], ...]) str¶
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
- Parameters:
params – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.
- Returns:
String representing the new class where params are passed to cls as type variables.
- Raises:
TypeError – Raised when trying to generate concrete names for non-generic models.
- model_post_init(_BaseModel__context: Any) None¶
Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.
- classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: dict[str, Any] | None = None) bool | None¶
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
- Parameters:
force – Whether to force the rebuilding of the model schema, defaults to False.
raise_errors – Whether to raise errors, defaults to True.
_parent_namespace_depth – The depth level of the parent namespace, defaults to 2.
_types_namespace – The types namespace, defaults to None.
- Returns:
Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.
- classmethod model_validate(obj: Any, *, strict: bool | None = None, from_attributes: bool | None = None, context: Any | None = None) Self¶
Validate a pydantic model instance.
- Parameters:
obj – The object to validate.
strict – Whether to enforce types strictly.
from_attributes – Whether to extract data from object attributes.
context – Additional context to pass to the validator.
- Raises:
ValidationError – If the object could not be validated.
- Returns:
The validated model instance.
- classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, context: Any | None = None) Self¶
Usage docs: https://docs.pydantic.dev/2.8/concepts/json/#json-parsing
Validate the given JSON data against the Pydantic model.
- Parameters:
json_data – The JSON data to validate.
strict – Whether to enforce types strictly.
context – Extra variables to pass to the validator.
- Returns:
The validated Pydantic model.
- Raises:
ValueError – If json_data is not a JSON string.
- classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, context: Any | None = None) Self¶
Validate the given object with string data against the Pydantic model.
- Parameters:
obj – The object containing string data to validate.
strict – Whether to enforce types strictly.
context – Extra variables to pass to the validator.
- Returns:
The validated Pydantic model.
- classmethod __get_pydantic_core_schema__(source: type[BaseModel], handler: GetCoreSchemaHandler, /) CoreSchema¶
Hook into generating the model’s CoreSchema.
- Parameters:
source – The class we are generating a schema for. This will generally be the same as the cls argument if this is a classmethod.
handler – A callable that calls into Pydantic’s internal CoreSchema generation logic.
- Returns:
A pydantic-core CoreSchema.
- classmethod __get_pydantic_json_schema__(core_schema: CoreSchema, handler: GetJsonSchemaHandler, /) JsonSchemaValue¶
Hook into generating the model’s JSON schema.
- Parameters:
core_schema – A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({‘type’: ‘nullable’, ‘schema’: current_schema}), or just call the handler with the original schema.
handler – Call into Pydantic’s internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.
- Returns:
A JSON schema, as a Python object.
- classmethod __pydantic_init_subclass__(**kwargs: Any) None¶
This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after the class is actually fully initialized. In particular, attributes like model_fields will be present when this is called.
This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.
This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren’t used internally by pydantic.
- Parameters:
**kwargs – Any keyword arguments passed to the class definition that aren’t used internally by pydantic.
- __pretty__(fmt: Callable[[Any], Any], **kwargs: Any) Generator[Any, None, None]¶
Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
- __rich_repr__() RichReprResult¶
Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
- dict(*, include: Set[int] | Set[str] | Dict[int, Any] | Dict[str, Any] | None = None, exclude: Set[int] | Set[str] | Dict[int, Any] | Dict[str, Any] | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) Dict[str, Any]¶
- json(*, include: Set[int] | Set[str] | Dict[int, Any] | Dict[str, Any] | None = None, exclude: Set[int] | Set[str] | Dict[int, Any] | Dict[str, Any] | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Callable[[Any], Any] | None = PydanticUndefined, models_as_dict: bool = PydanticUndefined, **dumps_kwargs: Any) str¶
- classmethod parse_raw(b: str | bytes, *, content_type: str | None = None, encoding: str = 'utf8', proto: DeprecatedParseProtocol | None = None, allow_pickle: bool = False) Self¶
- classmethod parse_file(path: str | Path, *, content_type: str | None = None, encoding: str = 'utf8', proto: DeprecatedParseProtocol | None = None, allow_pickle: bool = False) Self¶
- copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self¶
Returns a copy of the model.
- !!! warning “Deprecated”
This method is now deprecated; use model_copy instead.
If you need include or exclude, use:
`py data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `- Parameters:
include – Optional set or mapping specifying which fields to include in the copied model.
exclude – Optional set or mapping specifying which fields to exclude in the copied model.
update – Optional dictionary of field-value pairs to override field values in the copied model.
deep – If True, the values of fields that are Pydantic models will be deep-copied.
- Returns:
A copy of the model with included, excluded and updated fields as specified.
- class ConfigDict¶
A TypedDict for configuring Pydantic behaviour.
- model_title_generator: Callable[[type], str] | None¶
A callable that takes a model class and returns the title for it. Defaults to None.
- field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None¶
A callable that takes a field’s name and info and returns title for it. Defaults to None.
- str_to_lower: bool¶
Whether to convert all characters to lowercase for str types. Defaults to False.
- str_to_upper: bool¶
Whether to convert all characters to uppercase for str types. Defaults to False.
- extra: ExtraValues | None¶
Whether to ignore, allow, or forbid extra attributes during model initialization. Defaults to ‘ignore’.
You can configure how pydantic handles the attributes that are not defined in the model:
allow - Allow any extra attributes.
forbid - Forbid any extra attributes.
ignore - Ignore any extra attributes.
```py from pydantic import BaseModel, ConfigDict
- class User(BaseModel):
model_config = ConfigDict(extra=’ignore’) # (1)!
name: str
user = User(name=’John Doe’, age=20) # (2)! print(user) #> name=’John Doe’ ```
This is the default behaviour.
The age argument is ignored.
Instead, with extra=’allow’, the age argument is included:
```py from pydantic import BaseModel, ConfigDict
- class User(BaseModel):
model_config = ConfigDict(extra=’allow’)
name: str
user = User(name=’John Doe’, age=20) # (1)! print(user) #> name=’John Doe’ age=20 ```
The age argument is included.
With extra=’forbid’, an error is raised:
```py from pydantic import BaseModel, ConfigDict, ValidationError
- class User(BaseModel):
model_config = ConfigDict(extra=’forbid’)
name: str
- try:
User(name=’John Doe’, age=20)
- except ValidationError as e:
print(e) ‘’’ 1 validation error for User age Extra inputs are not permitted [type=extra_forbidden, input_value=20, input_type=int] ‘’’
- frozen: bool¶
Whether models are faux-immutable, i.e. whether __setattr__ is allowed, and also generates a __hash__() method for the model. This makes instances of the model potentially hashable if all the attributes are hashable. Defaults to False.
Note
On V1, the inverse of this setting was called allow_mutation, and was True by default.
- populate_by_name: bool¶
Whether an aliased field may be populated by its name as given by the model attribute, as well as the alias. Defaults to False.
Note
The name of this configuration setting was changed in v2.0 from allow_population_by_field_name to populate_by_name.
```py from pydantic import BaseModel, ConfigDict, Field
- class User(BaseModel):
model_config = ConfigDict(populate_by_name=True)
name: str = Field(alias=’full_name’) # (1)! age: int
user = User(full_name=’John Doe’, age=20) # (2)! print(user) #> name=’John Doe’ age=20 user = User(name=’John Doe’, age=20) # (3)! print(user) #> name=’John Doe’ age=20 ```
The field ‘name’ has an alias ‘full_name’.
The model is populated by the alias ‘full_name’.
The model is populated by the field name ‘name’.
- use_enum_values: bool¶
Whether to populate models with the value property of enums, rather than the raw enum. This may be useful if you want to serialize model.model_dump() later. Defaults to False.
- !!! note
If you have an Optional[Enum] value that you set a default for, you need to use validate_default=True for said Field to ensure that the use_enum_values flag takes effect on the default, as extracting an enum’s value occurs during validation, not serialization.
```py from enum import Enum from typing import Optional
from pydantic import BaseModel, ConfigDict, Field
- class SomeEnum(Enum):
FOO = ‘foo’ BAR = ‘bar’ BAZ = ‘baz’
- class SomeModel(BaseModel):
model_config = ConfigDict(use_enum_values=True)
some_enum: SomeEnum another_enum: Optional[SomeEnum] = Field(default=SomeEnum.FOO, validate_default=True)
model1 = SomeModel(some_enum=SomeEnum.BAR) print(model1.model_dump()) # {‘some_enum’: ‘bar’, ‘another_enum’: ‘foo’}
model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ) print(model2.model_dump()) #> {‘some_enum’: ‘bar’, ‘another_enum’: ‘baz’} ```
- validate_assignment: bool¶
Whether to validate the data when the model is changed. Defaults to False.
The default behavior of Pydantic is to validate the data when the model is created.
In case the user changes the data after the model is created, the model is _not_ revalidated.
```py from pydantic import BaseModel
- class User(BaseModel):
name: str
user = User(name=’John Doe’) # (1)! print(user) #> name=’John Doe’ user.name = 123 # (1)! print(user) #> name=123 ```
The validation happens only when the model is created.
The validation does not happen when the data is changed.
In case you want to revalidate the model when the data is changed, you can use validate_assignment=True:
```py from pydantic import BaseModel, ValidationError
- class User(BaseModel, validate_assignment=True): # (1)!
name: str
user = User(name=’John Doe’) # (2)! print(user) #> name=’John Doe’ try:
user.name = 123 # (3)!
- except ValidationError as e:
print(e) ‘’’ 1 validation error for User name
Input should be a valid string [type=string_type, input_value=123, input_type=int]
‘’’
You can either use class keyword arguments, or model_config to set validate_assignment=True.
The validation happens when the model is created.
The validation _also_ happens when the data is changed.
- arbitrary_types_allowed: bool¶
Whether arbitrary types are allowed for field types. Defaults to False.
```py from pydantic import BaseModel, ConfigDict, 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):
model_config = ConfigDict(arbitrary_types_allowed=True)
pet: Pet owner: str
pet = Pet(name=’Hedwig’) # A simple check of instance type is used to validate the data model = Model(owner=’Harry’, pet=pet) print(model) #> pet=<__main__.Pet object at 0x0123456789ab> owner=’Harry’ print(model.pet) #> <__main__.Pet object at 0x0123456789ab> print(model.pet.name) #> Hedwig print(type(model.pet)) #> <class ‘__main__.Pet’> try:
# If the value is not an instance of the type, it’s invalid Model(owner=’Harry’, pet=’Hedwig’)
- except ValidationError as e:
print(e) ‘’’ 1 validation error for Model pet
Input should be an instance of Pet [type=is_instance_of, input_value=’Hedwig’, input_type=str]
‘’’
# Nothing in the instance of the arbitrary type is checked # Here name probably should have been a str, but it’s not validated pet2 = Pet(name=42) model2 = Model(owner=’Harry’, pet=pet2) print(model2) #> pet=<__main__.Pet object at 0x0123456789ab> owner=’Harry’ print(model2.pet) #> <__main__.Pet object at 0x0123456789ab> print(model2.pet.name) #> 42 print(type(model2.pet)) #> <class ‘__main__.Pet’> ```
- from_attributes: bool¶
Whether to build models and look up discriminators of tagged unions using python object attributes.
- loc_by_alias: bool¶
Whether to use the actual key provided in the data (e.g. alias) for error loc`s rather than the field’s name. Defaults to `True.
- alias_generator: Callable[[str], str] | AliasGenerator | None¶
A callable that takes a field name and returns an alias for it or an instance of [AliasGenerator][pydantic.aliases.AliasGenerator]. Defaults to None.
When using a callable, the alias generator is used for both validation and serialization. If you want to use different alias generators for validation and serialization, you can use [AliasGenerator][pydantic.aliases.AliasGenerator] instead.
If data source field names do not match your code style (e. g. CamelCase fields), you can automatically generate aliases using alias_generator. Here’s an example with a basic callable:
```py from pydantic import BaseModel, ConfigDict from pydantic.alias_generators import to_pascal
- class Voice(BaseModel):
model_config = ConfigDict(alias_generator=to_pascal)
name: str language_code: str
voice = Voice(Name=’Filiz’, LanguageCode=’tr-TR’) print(voice.language_code) #> tr-TR print(voice.model_dump(by_alias=True)) #> {‘Name’: ‘Filiz’, ‘LanguageCode’: ‘tr-TR’} ```
If you want to use different alias generators for validation and serialization, you can use [AliasGenerator][pydantic.aliases.AliasGenerator].
```py from pydantic import AliasGenerator, BaseModel, ConfigDict from pydantic.alias_generators import to_camel, to_pascal
- class Athlete(BaseModel):
first_name: str last_name: str sport: str
- model_config = ConfigDict(
- alias_generator=AliasGenerator(
validation_alias=to_camel, serialization_alias=to_pascal,
)
)
athlete = Athlete(firstName=’John’, lastName=’Doe’, sport=’track’) print(athlete.model_dump(by_alias=True)) #> {‘FirstName’: ‘John’, ‘LastName’: ‘Doe’, ‘Sport’: ‘track’} ```
Note
Pydantic offers three built-in alias generators: [to_pascal][pydantic.alias_generators.to_pascal], [to_camel][pydantic.alias_generators.to_camel], and [to_snake][pydantic.alias_generators.to_snake].
- ignored_types: tuple[type, ...]¶
A tuple of types that may occur as values of class attributes without annotations. This is typically used for custom descriptors (classes that behave like property). If an attribute is set on a class without an annotation and has a type that is not in this tuple (or otherwise recognized by _pydantic_), an error will be raised. Defaults to ().
- allow_inf_nan: bool¶
Whether to allow infinity (+inf an -inf) and NaN values to float fields. Defaults to True.
- json_schema_extra: JsonDict | JsonSchemaExtraCallable | None¶
A dict or callable to provide extra JSON schema properties. Defaults to None.
- json_encoders: dict[type[object], JsonEncoder] | None¶
A dict of custom JSON encoders for specific types. Defaults to None.
- !!! warning “Deprecated”
This config option is a carryover from v1. We originally planned to remove it in v2 but didn’t have a 1:1 replacement so we are keeping it for now. It is still deprecated and will likely be removed in the future.
- strict: bool¶
_(new in V2)_ If True, strict validation is applied to all fields on the model.
By default, Pydantic attempts to coerce values to the correct type, when possible.
There are situations in which you may want to disable this behavior, and instead raise an error if a value’s type does not match the field’s type annotation.
To configure strict mode for all fields on a model, you can set strict=True on the model.
```py from pydantic import BaseModel, ConfigDict
- class Model(BaseModel):
model_config = ConfigDict(strict=True)
name: str age: int
See [Strict Mode](../concepts/strict_mode.md) for more details.
See the [Conversion Table](../concepts/conversion_table.md) for more details on how Pydantic converts data in both strict and lax modes.
- revalidate_instances: Literal['always', 'never', 'subclass-instances']¶
When and how to revalidate models and dataclasses during validation. Accepts the string values of ‘never’, ‘always’ and ‘subclass-instances’. Defaults to ‘never’.
‘never’ will not revalidate models and dataclasses during validation
‘always’ will revalidate models and dataclasses during validation
- ‘subclass-instances’ will revalidate models and dataclasses during validation if the instance is a
subclass of the model or dataclass
By default, model and dataclass instances are not revalidated during validation.
from pydantic import BaseModel
- class User(BaseModel, revalidate_instances=’never’): # (1)!
hobbies: List[str]
- class SubUser(User):
sins: List[str]
- class Transaction(BaseModel):
user: User
my_user = User(hobbies=[‘reading’]) t = Transaction(user=my_user) print(t) #> user=User(hobbies=[‘reading’])
my_user.hobbies = [1] # (2)! t = Transaction(user=my_user) # (3)! print(t) #> user=User(hobbies=[1])
my_sub_user = SubUser(hobbies=[‘scuba diving’], sins=[‘lying’]) t = Transaction(user=my_sub_user) print(t) #> user=SubUser(hobbies=[‘scuba diving’], sins=[‘lying’]) ```
revalidate_instances is set to ‘never’ by **default.
The assignment is not validated, unless you set validate_assignment to True in the model’s config.
Since revalidate_instances is set to never, this is not revalidated.
If you want to revalidate instances during validation, you can set revalidate_instances to ‘always’ in the model’s config.
from pydantic import BaseModel, ValidationError
- class User(BaseModel, revalidate_instances=’always’): # (1)!
hobbies: List[str]
- class SubUser(User):
sins: List[str]
- class Transaction(BaseModel):
user: User
my_user = User(hobbies=[‘reading’]) t = Transaction(user=my_user) print(t) #> user=User(hobbies=[‘reading’])
my_user.hobbies = [1] try:
t = Transaction(user=my_user) # (2)!
- except ValidationError as e:
print(e) ‘’’ 1 validation error for Transaction user.hobbies.0
Input should be a valid string [type=string_type, input_value=1, input_type=int]
‘’’
my_sub_user = SubUser(hobbies=[‘scuba diving’], sins=[‘lying’]) t = Transaction(user=my_sub_user) print(t) # (3)! #> user=User(hobbies=[‘scuba diving’]) ```
revalidate_instances is set to ‘always’.
The model is revalidated, since revalidate_instances is set to ‘always’.
Using ‘never’ we would have gotten user=SubUser(hobbies=[‘scuba diving’], sins=[‘lying’]).
It’s also possible to set revalidate_instances to ‘subclass-instances’ to only revalidate instances of subclasses of the model.
from pydantic import BaseModel
- class User(BaseModel, revalidate_instances=’subclass-instances’): # (1)!
hobbies: List[str]
- class SubUser(User):
sins: List[str]
- class Transaction(BaseModel):
user: User
my_user = User(hobbies=[‘reading’]) t = Transaction(user=my_user) print(t) #> user=User(hobbies=[‘reading’])
my_user.hobbies = [1] t = Transaction(user=my_user) # (2)! print(t) #> user=User(hobbies=[1])
my_sub_user = SubUser(hobbies=[‘scuba diving’], sins=[‘lying’]) t = Transaction(user=my_sub_user) print(t) # (3)! #> user=User(hobbies=[‘scuba diving’]) ```
revalidate_instances is set to ‘subclass-instances’.
This is not revalidated, since my_user is not a subclass of User.
Using ‘never’ we would have gotten user=SubUser(hobbies=[‘scuba diving’], sins=[‘lying’]).
- ser_json_timedelta: Literal['iso8601', 'float']¶
The format of JSON serialized timedeltas. Accepts the string values of ‘iso8601’ and ‘float’. Defaults to ‘iso8601’.
‘iso8601’ will serialize timedeltas to ISO 8601 durations.
‘float’ will serialize timedeltas to the total number of seconds.
- ser_json_bytes: Literal['utf8', 'base64']¶
The encoding of JSON serialized bytes. Accepts the string values of ‘utf8’ and ‘base64’. Defaults to ‘utf8’.
‘utf8’ will serialize bytes to UTF-8 strings.
‘base64’ will serialize bytes to URL safe base64 strings.
- ser_json_inf_nan: Literal['null', 'constants', 'strings']¶
The encoding of JSON serialized infinity and NaN float values. Defaults to ‘null’.
‘null’ will serialize infinity and NaN values as null.
‘constants’ will serialize infinity and NaN values as Infinity and NaN.
‘strings’ will serialize infinity as string “Infinity” and NaN as string “NaN”.
- validate_return: bool¶
whether to validate the return value from call validators. Defaults to False.
- protected_namespaces: tuple[str, ...]¶
A tuple of strings that prevent model to have field which conflict with them. Defaults to (‘model_’, )).
Pydantic prevents collisions between model attributes and BaseModel’s own methods by namespacing them with the prefix model_.
from pydantic import BaseModel
warnings.filterwarnings(‘error’) # Raise warnings as errors
try:
- class Model(BaseModel):
model_prefixed_field: str
- except UserWarning as e:
print(e) ‘’’ Field “model_prefixed_field” has conflict with protected namespace “model_”.
You may be able to resolve this warning by setting model_config[‘protected_namespaces’] = (). ‘’’
You can customize this behavior using the protected_namespaces setting:
from pydantic import BaseModel, ConfigDict
warnings.filterwarnings(‘error’) # Raise warnings as errors
try:
- class Model(BaseModel):
model_prefixed_field: str also_protect_field: str
- model_config = ConfigDict(
protected_namespaces=(’protect_me_’, ‘also_protect_’)
)
- except UserWarning as e:
print(e) ‘’’ Field “also_protect_field” has conflict with protected namespace “also_protect_”.
You may be able to resolve this warning by setting model_config[‘protected_namespaces’] = (‘protect_me_’,). ‘’’
While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision, an error _is_ raised if there is an actual collision with an existing attribute:
```py from pydantic import BaseModel
try:
- class Model(BaseModel):
model_validate: str
- except NameError as e:
print(e) ‘’’ Field “model_validate” conflicts with member <bound method BaseModel.model_validate of <class ‘pydantic.main.BaseModel’>> of protected namespace “model_”. ‘’’
- hide_input_in_errors: bool¶
Whether to hide inputs when printing errors. Defaults to False.
Pydantic shows the input value and type when it raises ValidationError during the validation.
```py from pydantic import BaseModel, ValidationError
- class Model(BaseModel):
a: str
- try:
Model(a=123)
- except ValidationError as e:
print(e) ‘’’ 1 validation error for Model a
Input should be a valid string [type=string_type, input_value=123, input_type=int]
‘’’
You can hide the input value and type by setting the hide_input_in_errors config to True.
```py from pydantic import BaseModel, ConfigDict, ValidationError
- class Model(BaseModel):
a: str model_config = ConfigDict(hide_input_in_errors=True)
- try:
Model(a=123)
- except ValidationError as e:
print(e) ‘’’ 1 validation error for Model a
Input should be a valid string [type=string_type]
‘’’
- defer_build: bool¶
Whether to defer model validator and serializer construction until the first model validation. Defaults to False.
This can be useful to avoid the overhead of building models which are only used nested within other models, or when you want to manually define type namespace via [Model.model_rebuild(_types_namespace=…)][pydantic.BaseModel.model_rebuild].
See also [experimental_defer_build_mode][pydantic.config.ConfigDict.experimental_defer_build_mode].
- !!! note
defer_build does not work by default with FastAPI Pydantic models. By default, the validator and serializer for said models is constructed immediately for FastAPI routes. You also need to define [experimental_defer_build_mode=(‘model’, ‘type_adapter’)][pydantic.config.ConfigDict.experimental_defer_build_mode] with FastAPI models in order for defer_build=True to take effect. This additional (experimental) parameter is required for the deferred building due to FastAPI relying on `TypeAdapter`s.
- experimental_defer_build_mode: tuple[Literal['model', 'type_adapter'], ...]¶
Controls when [defer_build][pydantic.config.ConfigDict.defer_build] is applicable. Defaults to (‘model’,).
Due to backwards compatibility reasons [TypeAdapter][pydantic.type_adapter.TypeAdapter] does not by default respect defer_build. Meaning when defer_build is True and experimental_defer_build_mode is the default (‘model’,) then TypeAdapter immediately constructs its validator and serializer instead of postponing said construction until the first model validation. Set this to (‘model’, ‘type_adapter’) to make TypeAdapter respect the defer_build so it postpones validator and serializer construction until the first validation or serialization.
- !!! note
The experimental_defer_build_mode parameter is named with an underscore to suggest this is an experimental feature. It may be removed or changed in the future in a minor release.
- plugin_settings: dict[str, object] | None¶
A dict of settings for plugins. Defaults to None.
See [Pydantic Plugins](../concepts/plugins.md) for details.
- schema_generator: type[_GenerateSchema] | None¶
A custom core schema generator class to use when generating JSON schemas. Useful if you want to change the way types are validated across an entire model/schema. Defaults to None.
The GenerateSchema interface is subject to change, currently only the string_schema method is public.
See [#6737](https://github.com/pydantic/pydantic/pull/6737) for details.
- json_schema_serialization_defaults_required: bool¶
Whether fields with default values should be marked as required in the serialization schema. Defaults to False.
This ensures that the serialization schema will reflect the fact a field with a default will always be present when serializing the model, even though it is not required for validation.
However, there are scenarios where this may be undesirable — in particular, if you want to share the schema between validation and serialization, and don’t mind fields with defaults being marked as not required during serialization. See [#7209](https://github.com/pydantic/pydantic/issues/7209) for more details.
```py from pydantic import BaseModel, ConfigDict
- class Model(BaseModel):
a: str = ‘a’
model_config = ConfigDict(json_schema_serialization_defaults_required=True)
print(Model.model_json_schema(mode=’validation’)) ‘’’ {
‘properties’: {‘a’: {‘default’: ‘a’, ‘title’: ‘A’, ‘type’: ‘string’}}, ‘title’: ‘Model’, ‘type’: ‘object’,
}¶
print(Model.model_json_schema(mode=’serialization’)) ‘’’ {
‘properties’: {‘a’: {‘default’: ‘a’, ‘title’: ‘A’, ‘type’: ‘string’}}, ‘required’: [‘a’], ‘title’: ‘Model’, ‘type’: ‘object’,
}¶
- json_schema_mode_override: Literal['validation', 'serialization', None]¶
If not None, the specified mode will be used to generate the JSON schema regardless of what mode was passed to the function call. Defaults to None.
This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the validation schema.
It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation and serialization that must both be referenced from the same schema; when this happens, we automatically append -Input to the definition reference for the validation schema and -Output to the definition reference for the serialization schema. By specifying a json_schema_mode_override though, this prevents the conflict between the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes from being added to the definition references.
```py from pydantic import BaseModel, ConfigDict, Json
- class Model(BaseModel):
a: Json[int] # requires a string to validate, but will dump an int
print(Model.model_json_schema(mode=’serialization’)) ‘’’ {
‘properties’: {‘a’: {‘title’: ‘A’, ‘type’: ‘integer’}}, ‘required’: [‘a’], ‘title’: ‘Model’, ‘type’: ‘object’,
}¶
- class ForceInputModel(Model):
# the following ensures that even with mode=’serialization’, we # will get the schema that would be generated for validation. model_config = ConfigDict(json_schema_mode_override=’validation’)
print(ForceInputModel.model_json_schema(mode=’serialization’)) ‘’’ {
- ‘properties’: {
- ‘a’: {
‘contentMediaType’: ‘application/json’, ‘contentSchema’: {‘type’: ‘integer’}, ‘title’: ‘A’, ‘type’: ‘string’,
}
}, ‘required’: [‘a’], ‘title’: ‘ForceInputModel’, ‘type’: ‘object’,
}¶
- coerce_numbers_to_str: bool¶
If True, enables automatic coercion of any Number type to str in “lax” (non-strict) mode. Defaults to False.
Pydantic doesn’t allow number types (int, float, Decimal) to be coerced as type str by default.
```py from decimal import Decimal
from pydantic import BaseModel, ConfigDict, ValidationError
- class Model(BaseModel):
value: str
- try:
print(Model(value=42))
- except ValidationError as e:
print(e) ‘’’ 1 validation error for Model value
Input should be a valid string [type=string_type, input_value=42, input_type=int]
‘’’
- class Model(BaseModel):
model_config = ConfigDict(coerce_numbers_to_str=True)
value: str
repr(Model(value=42).value) #> “42” repr(Model(value=42.13).value) #> “42.13” repr(Model(value=Decimal(‘42.13’)).value) #> “42.13” ```
- regex_engine: Literal['rust-regex', 'python-re']¶
The regex engine to be used for pattern validation. Defaults to ‘rust-regex’.
rust-regex uses the [regex](https://docs.rs/regex) Rust crate, which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.
python-re use the [re](https://docs.python.org/3/library/re.html) module, which supports all regex features, but may be slower.
- !!! note
If you use a compiled regex pattern, the python-re engine will be used regardless of this setting. This is so that flags such as re.IGNORECASE are respected.
```py from pydantic import BaseModel, ConfigDict, Field, ValidationError
- class Model(BaseModel):
model_config = ConfigDict(regex_engine=’python-re’)
value: str = Field(pattern=r’^abc(?=def)’)
print(Model(value=’abcdef’).value) #> abcdef
- try:
print(Model(value=’abxyzcdef’))
- except ValidationError as e:
print(e) ‘’’ 1 validation error for Model value
String should match pattern ‘^abc(?=def)’ [type=string_pattern_mismatch, input_value=’abxyzcdef’, input_type=str]
‘’’
- validation_error_cause: bool¶
If True, Python exceptions that were part of a validation failure will be shown as an exception group as a cause. Can be useful for debugging. Defaults to False.
Note
Python 3.10 and older don’t support exception groups natively. <=3.10, backport must be installed: pip install exceptiongroup.
Note
The structure of validation errors are likely to change in future Pydantic versions. Pydantic offers no guarantees about their structure. Should be used for visual traceback debugging only.
- use_attribute_docstrings: bool¶
Whether docstrings of attributes (bare string literals immediately following the attribute declaration) should be used for field descriptions. Defaults to False.
Available in Pydantic v2.7+.
```py from pydantic import BaseModel, ConfigDict, Field
- class Model(BaseModel):
model_config = ConfigDict(use_attribute_docstrings=True)
x: str “”” Example of an attribute docstring “””
y: int = Field(description=”Description in Field”) “”” Description in Field overrides attribute docstring “””
print(Model.model_fields[“x”].description) # > Example of an attribute docstring print(Model.model_fields[“y”].description) # > Description in Field ``` This requires the source code of the class to be available at runtime.
- !!! warning “Usage with TypedDict”
Due to current limitations, attribute docstrings detection may not work as expected when using TypedDict (in particular when multiple TypedDict classes have the same name in the same source file). The behavior can be different depending on the Python version used.
- cache_strings: bool | Literal['all', 'keys', 'none']¶
Whether to cache strings to avoid constructing new Python objects. Defaults to True.
Enabling this setting should significantly improve validation performance while increasing memory usage slightly.
True or ‘all’ (the default): cache all strings
‘keys’: cache only dictionary keys
False or ‘none’: no caching
- !!! note
True or ‘all’ is required to cache strings during general validation because validators don’t know if they’re in a key or a value.
- !!! tip
If repeated strings are rare, it’s recommended to use ‘keys’ or ‘none’ to reduce memory usage, as the performance difference is minimal if repeated strings are rare.
- Field(default: Any = PydanticUndefined, *, default_factory: Callable[[], Any] | None = PydanticUndefined, alias: str | None = PydanticUndefined, alias_priority: int | None = PydanticUndefined, validation_alias: str | AliasPath | AliasChoices | None = PydanticUndefined, serialization_alias: str | None = PydanticUndefined, title: str | None = PydanticUndefined, field_title_generator: typing_extensions.Callable[[str, FieldInfo], str] | None = PydanticUndefined, description: str | None = PydanticUndefined, examples: list[Any] | None = PydanticUndefined, exclude: bool | None = PydanticUndefined, discriminator: str | types.Discriminator | None = PydanticUndefined, deprecated: Deprecated | str | bool | None = PydanticUndefined, json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = PydanticUndefined, frozen: bool | None = PydanticUndefined, validate_default: bool | None = PydanticUndefined, repr: bool = PydanticUndefined, init: bool | None = PydanticUndefined, init_var: bool | None = PydanticUndefined, kw_only: bool | None = PydanticUndefined, pattern: str | Pattern[str] | None = PydanticUndefined, strict: bool | None = PydanticUndefined, coerce_numbers_to_str: bool | None = PydanticUndefined, gt: annotated_types.SupportsGt | None = PydanticUndefined, ge: annotated_types.SupportsGe | None = PydanticUndefined, lt: annotated_types.SupportsLt | None = PydanticUndefined, le: annotated_types.SupportsLe | None = PydanticUndefined, multiple_of: float | None = PydanticUndefined, allow_inf_nan: bool | None = PydanticUndefined, max_digits: int | None = PydanticUndefined, decimal_places: int | None = PydanticUndefined, min_length: int | None = PydanticUndefined, max_length: int | None = PydanticUndefined, union_mode: Literal['smart', 'left_to_right'] = PydanticUndefined, fail_fast: bool | None = PydanticUndefined, **extra: Unpack[_EmptyKwargs]) Any¶
Usage docs: https://docs.pydantic.dev/2.8/concepts/fields
Create a field for objects that can be configured.
Used to provide extra information about a field, either for the model schema or complex validation. Some arguments apply only to number fields (int, float, Decimal) and some apply only to str.
Note
Any _Unset objects will be replaced by the corresponding value defined in the _DefaultValues dictionary. If a key for the _Unset object is not found in the _DefaultValues dictionary, it will default to None
- Parameters:
default – Default value if the field is not set.
default_factory – A callable to generate the default value, such as
utcnow().alias – The name to use for the attribute when validating or serializing by alias. This is often used for things like converting between snake and camel case.
alias_priority – Priority of the alias. This affects whether an alias generator is used.
validation_alias – Like alias, but only affects validation, not serialization.
serialization_alias – Like alias, but only affects serialization, not validation.
title – Human-readable title.
field_title_generator – A callable that takes a field name and returns title for it.
description – Human-readable description.
examples – Example values for this field.
exclude – Whether to exclude the field from the model serialization.
discriminator – Field name or Discriminator for discriminating the type in a tagged union.
deprecated – A deprecation message, an instance of warnings.deprecated or the typing_extensions.deprecated backport, or a boolean. If True, a default deprecation message will be emitted when accessing the field.
json_schema_extra – A dict or callable to provide extra JSON schema properties.
frozen – Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.
validate_default – If True, apply validation to the default value every time you create an instance. Otherwise, for performance reasons, the default value of the field is trusted and not validated.
repr – A boolean indicating whether to include the field in the __repr__ output.
init – Whether the field should be included in the constructor of the dataclass. (Only applies to dataclasses.)
init_var – Whether the field should _only_ be included in the constructor of the dataclass. (Only applies to dataclasses.)
kw_only – Whether the field should be a keyword-only argument in the constructor of the dataclass. (Only applies to dataclasses.)
coerce_numbers_to_str – Whether to enable coercion of any Number type to str (not applicable in strict mode).
strict – If True, strict validation is applied to the field. See [Strict Mode](../concepts/strict_mode.md) for details.
gt – Greater than. If set, value must be greater than this. Only applicable to numbers.
ge – Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.
lt – Less than. If set, value must be less than this. Only applicable to numbers.
le – Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.
multiple_of – Value must be a multiple of this. Only applicable to numbers.
min_length – Minimum length for iterables.
max_length – Maximum length for iterables.
pattern – Pattern for strings (a regular expression).
allow_inf_nan – Allow inf, -inf, nan. Only applicable to numbers.
max_digits – Maximum number of allow digits for strings.
decimal_places – Maximum number of decimal places allowed for numbers.
union_mode – The strategy to apply when validating a union. Can be smart (the default), or left_to_right. See [Union Mode](../concepts/unions.md#union-modes) for details.
fail_fast – If True, validation will stop on the first error. If False, all validation errors will be collected. This option can be applied only to iterable types (list, tuple, set, and frozenset).
extra –
(Deprecated) Extra fields that will be included in the JSON schema.
- !!! warning Deprecated
The extra kwargs is deprecated. Use json_schema_extra instead.
- Returns:
- A new [FieldInfo][pydantic.fields.FieldInfo]. The return annotation is Any so Field can be used on
type-annotated fields without causing a type error.
- class RootModel(root: RootModelRootType = PydanticUndefined)¶
Usage docs: https://docs.pydantic.dev/2.8/concepts/models/#rootmodel-and-custom-root-types
A Pydantic BaseModel for the root object of the model.
- root¶
The root object of the model.
- Type:
RootModelRootType
- __pydantic_root_model__¶
Whether the model is a RootModel.
- __pydantic_private__¶
Private fields in the model.
- __pydantic_extra__¶
Extra fields in the model.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- root: RootModelRootType¶
- classmethod model_construct(root: RootModelRootType, _fields_set: set[str] | None = None) Self¶
Create a new model using the provided root object and update fields set.
- Parameters:
root – The root object of the model.
_fields_set – The set of fields to be updated.
- Returns:
The new model.
- Raises:
NotImplemented – If the model is not a subclass of RootModel.
- __copy__() Self¶
Returns a shallow copy of the model.
- model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}¶
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- field_validator(field: str, /, *fields: str, mode: Literal['before', 'after', 'wrap', 'plain'] = 'after', check_fields: bool | None = None) Callable[[Any], Any]¶
Usage docs: https://docs.pydantic.dev/2.8/concepts/validators/#field-validators
Decorate methods on the class indicating that they should be used to validate fields.
Example usage: ```py from typing import Any
- from pydantic import (
BaseModel, ValidationError, field_validator,
)
- class Model(BaseModel):
a: str
@field_validator(‘a’) @classmethod def ensure_foobar(cls, v: Any):
- if ‘foobar’ not in v:
raise ValueError(‘“foobar” not found in a’)
return v
print(repr(Model(a=’this is foobar good’))) #> Model(a=’this is foobar good’)
- try:
Model(a=’snap’)
- except ValidationError as exc_info:
print(exc_info) ‘’’ 1 validation error for Model a
Value error, “foobar” not found in a [type=value_error, input_value=’snap’, input_type=str]
‘’’
For more in depth examples, see [Field Validators](../concepts/validators.md#field-validators).
- Parameters:
field – The first field the field_validator should be called on; this is separate from fields to ensure an error is raised if you don’t pass at least one.
*fields – Additional field(s) the field_validator should be called on.
mode – Specifies whether to validate the fields before or after validation.
check_fields – Whether to check that the fields actually exist on the model.
- Returns:
A decorator that can be used to decorate a function to be used as a field_validator.
- Raises:
PydanticUserError –
If @field_validator is used bare (with no fields). - If the args passed to @field_validator as fields are not strings. - If @field_validator applied to instance methods.
- class CSRMatrix(*, hdf5_path: str | None = None, object_id: str | None = None, name: str, shape: ~numpy.uint64 | None = None, indices: ~nptyping.base_meta_classes.NDArray[~nptyping.base_meta_classes.Shape[* number_of_non_zero_values], ~numpy.uint64], indptr: ~nptyping.base_meta_classes.NDArray[~nptyping.base_meta_classes.Shape[* number_of_rows_in_the_matrix_1], ~numpy.uint64], data: ~nwb_linkml.models.pydantic.hdmf_common.v1_5_0.hdmf_common_sparse.CSRMatrixData)¶
A compressed sparse row matrix. Data are stored in the standard CSR format, where column indices for row i are stored in indices[indptr[i]:indptr[i+1]] and their corresponding values are stored in data[indptr[i]:indptr[i+1]].
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- linkml_meta: ClassVar[LinkMLMeta] = LinkMLMeta(root={'from_schema': 'hdmf-common.sparse', 'tree_root': True})¶
- indices: NDArray[Shape['* number_of_non_zero_values'], np.uint64]¶
- indptr: NDArray[Shape['* number_of_rows_in_the_matrix_1'], np.uint64]¶
- data: CSRMatrixData¶
- model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}¶
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'strict': False, 'use_enum_values': True, 'validate_assignment': True, 'validate_default': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'data': FieldInfo(annotation=CSRMatrixData, required=True, description='The non-zero values in the matrix.'), 'hdf5_path': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='The absolute path that this object is stored in an NWB file'), 'indices': FieldInfo(annotation=NDArray, required=True, description='The column indices.', json_schema_extra={'linkml_meta': {'array': {'dimensions': [{'alias': 'number_of_non_zero_values'}]}}}), 'indptr': FieldInfo(annotation=NDArray, required=True, description='The row index pointer.', json_schema_extra={'linkml_meta': {'array': {'dimensions': [{'alias': 'number_of_rows_in_the_matrix_1'}]}}}), 'name': FieldInfo(annotation=str, required=True), 'object_id': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Unique UUID for each object'), 'shape': FieldInfo(annotation=Union[uint64, NoneType], required=False, default=None, description='The shape (number of rows, number of columns) of this sparse matrix.')}¶
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class CSRMatrixData(*, hdf5_path: str | None = None, object_id: str | None = None, name: Literal['data'] = 'data')¶
The non-zero values in the matrix.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- linkml_meta: ClassVar[LinkMLMeta] = LinkMLMeta(root={'from_schema': 'hdmf-common.sparse'})¶
- name: Literal['data']¶
- model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}¶
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'strict': False, 'use_enum_values': True, 'validate_assignment': True, 'validate_default': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'hdf5_path': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='The absolute path that this object is stored in an NWB file'), 'name': FieldInfo(annotation=Literal['data'], required=False, default='data', json_schema_extra={'linkml_meta': {'equals_string': 'data', 'ifabsent': 'string(data)'}}), 'object_id': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Unique UUID for each object')}¶
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class Data(*, hdf5_path: str | None = None, object_id: str | None = None, name: str)¶
An abstract data type for a dataset.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- linkml_meta: ClassVar[LinkMLMeta] = LinkMLMeta(root={'from_schema': 'hdmf-common.base', 'tree_root': True})¶
- model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}¶
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'strict': False, 'use_enum_values': True, 'validate_assignment': True, 'validate_default': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'hdf5_path': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='The absolute path that this object is stored in an NWB file'), 'name': FieldInfo(annotation=str, required=True), 'object_id': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Unique UUID for each object')}¶
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class Container(*, hdf5_path: str | None = None, object_id: str | None = None, name: str)¶
An abstract data type for a group storing collections of data and metadata. Base type for all data and metadata containers.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- linkml_meta: ClassVar[LinkMLMeta] = LinkMLMeta(root={'from_schema': 'hdmf-common.base', 'tree_root': True})¶
- model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}¶
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'strict': False, 'use_enum_values': True, 'validate_assignment': True, 'validate_default': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'hdf5_path': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='The absolute path that this object is stored in an NWB file'), 'name': FieldInfo(annotation=str, required=True), 'object_id': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Unique UUID for each object')}¶
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class SimpleMultiContainer(*, hdf5_path: str | None = None, object_id: str | None = None, name: str, children: List[Container] | None = None)¶
A simple Container for holding onto multiple containers.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- linkml_meta: ClassVar[LinkMLMeta] = LinkMLMeta(root={'from_schema': 'hdmf-common.base', 'tree_root': True})¶
- model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}¶
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'strict': False, 'use_enum_values': True, 'validate_assignment': True, 'validate_default': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'children': FieldInfo(annotation=Union[List[Container], NoneType], required=False, default=None, json_schema_extra={'linkml_meta': {'any_of': [{'range': 'Container'}]}}), 'hdf5_path': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='The absolute path that this object is stored in an NWB file'), 'name': FieldInfo(annotation=str, required=True), 'object_id': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Unique UUID for each object')}¶
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class VectorData(*, hdf5_path: str | None = None, object_id: str | None = None, name: str, description: str | None = None, array: ~nptyping.base_meta_classes.NDArray[~nptyping.base_meta_classes.Shape[* dim0], ~typing.Any] | ~nptyping.base_meta_classes.NDArray[~nptyping.base_meta_classes.Shape[* dim0, * dim1], ~typing.Any] | ~nptyping.base_meta_classes.NDArray[~nptyping.base_meta_classes.Shape[* dim0, * dim1, * dim2], ~typing.Any] | ~nptyping.base_meta_classes.NDArray[~nptyping.base_meta_classes.Shape[* dim0, * dim1, * dim2, * dim3], ~typing.Any] | None = None)¶
An n-dimensional dataset representing a column of a DynamicTable. If used without an accompanying VectorIndex, first dimension is along the rows of the DynamicTable and each step along the first dimension is a cell of the larger table. VectorData can also be used to represent a ragged array if paired with a VectorIndex. This allows for storing arrays of varying length in a single cell of the DynamicTable by indexing into this VectorData. The first vector is at VectorData[0:VectorIndex[0]]. The second vector is at VectorData[VectorIndex[0]:VectorIndex[1]], and so on.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- linkml_meta: ClassVar[LinkMLMeta] = LinkMLMeta(root={'from_schema': 'hdmf-common.table', 'tree_root': True})¶
- array: NDArray[Shape['* dim0'], Any] | NDArray[Shape['* dim0, * dim1'], Any] | NDArray[Shape['* dim0, * dim1, * dim2'], Any] | NDArray[Shape['* dim0, * dim1, * dim2, * dim3'], Any] | None¶
- model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}¶
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'strict': False, 'use_enum_values': True, 'validate_assignment': True, 'validate_default': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'array': FieldInfo(annotation=Union[NDArray, NDArray, NDArray, NDArray, NoneType], required=False, default=None), 'description': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Description of what these vectors represent.'), 'hdf5_path': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='The absolute path that this object is stored in an NWB file'), 'name': FieldInfo(annotation=str, required=True), 'object_id': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Unique UUID for each object')}¶
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class VectorIndex(*, hdf5_path: str | None = None, object_id: str | None = None, name: str, description: str | None = None, array: ~nptyping.base_meta_classes.NDArray[~nptyping.base_meta_classes.Shape[* dim0], ~typing.Any] | ~nptyping.base_meta_classes.NDArray[~nptyping.base_meta_classes.Shape[* dim0, * dim1], ~typing.Any] | ~nptyping.base_meta_classes.NDArray[~nptyping.base_meta_classes.Shape[* dim0, * dim1, * dim2], ~typing.Any] | ~nptyping.base_meta_classes.NDArray[~nptyping.base_meta_classes.Shape[* dim0, * dim1, * dim2, * dim3], ~typing.Any] | None = None, target: ~nwb_linkml.models.pydantic.hdmf_common.v1_5_0.hdmf_common_table.VectorData | None = None)¶
Used with VectorData to encode a ragged array. An array of indices into the first dimension of the target VectorData, and forming a map between the rows of a DynamicTable and the indices of the VectorData. The name of the VectorIndex is expected to be the name of the target VectorData object followed by “_index”.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- linkml_meta: ClassVar[LinkMLMeta] = LinkMLMeta(root={'from_schema': 'hdmf-common.table', 'tree_root': True})¶
- target: VectorData | None¶
- array: NDArray[Shape['* dim0'], Any] | NDArray[Shape['* dim0, * dim1'], Any] | NDArray[Shape['* dim0, * dim1, * dim2'], Any] | NDArray[Shape['* dim0, * dim1, * dim2, * dim3'], Any] | None¶
- model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}¶
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'strict': False, 'use_enum_values': True, 'validate_assignment': True, 'validate_default': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'array': FieldInfo(annotation=Union[NDArray, NDArray, NDArray, NDArray, NoneType], required=False, default=None), 'description': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Description of what these vectors represent.'), 'hdf5_path': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='The absolute path that this object is stored in an NWB file'), 'name': FieldInfo(annotation=str, required=True), 'object_id': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Unique UUID for each object'), 'target': FieldInfo(annotation=Union[VectorData, NoneType], required=False, default=None, description='Reference to the target dataset that this index applies to.')}¶
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class ElementIdentifiers(*, hdf5_path: str | None = None, object_id: str | None = None, name: str = 'element_id')¶
A list of unique identifiers for values within a dataset, e.g. rows of a DynamicTable.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- linkml_meta: ClassVar[LinkMLMeta] = LinkMLMeta(root={'from_schema': 'hdmf-common.table', 'tree_root': True})¶
- model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}¶
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'strict': False, 'use_enum_values': True, 'validate_assignment': True, 'validate_default': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'hdf5_path': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='The absolute path that this object is stored in an NWB file'), 'name': FieldInfo(annotation=str, required=False, default='element_id', json_schema_extra={'linkml_meta': {'ifabsent': 'string(element_id)'}}), 'object_id': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Unique UUID for each object')}¶
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class DynamicTableRegion(*, hdf5_path: str | None = None, object_id: str | None = None, name: str, description: str | None = None, array: ~nptyping.base_meta_classes.NDArray[~nptyping.base_meta_classes.Shape[* dim0], ~typing.Any] | ~nptyping.base_meta_classes.NDArray[~nptyping.base_meta_classes.Shape[* dim0, * dim1], ~typing.Any] | ~nptyping.base_meta_classes.NDArray[~nptyping.base_meta_classes.Shape[* dim0, * dim1, * dim2], ~typing.Any] | ~nptyping.base_meta_classes.NDArray[~nptyping.base_meta_classes.Shape[* dim0, * dim1, * dim2, * dim3], ~typing.Any] | None = None, table: ~nwb_linkml.models.pydantic.hdmf_common.v1_5_0.hdmf_common_table.DynamicTable | None = None)¶
DynamicTableRegion provides a link from one table to an index or region of another. The table attribute is a link to another DynamicTable, indicating which table is referenced, and the data is int(s) indicating the row(s) (0-indexed) of the target array. DynamicTableRegion`s can be used to associate rows with repeated meta-data without data duplication. They can also be used to create hierarchical relationships between multiple `DynamicTable`s. `DynamicTableRegion objects may be paired with a VectorIndex object to create ragged references, so a single cell of a DynamicTable can reference many rows of another DynamicTable.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- linkml_meta: ClassVar[LinkMLMeta] = LinkMLMeta(root={'from_schema': 'hdmf-common.table', 'tree_root': True})¶
- array: NDArray[Shape['* dim0'], Any] | NDArray[Shape['* dim0, * dim1'], Any] | NDArray[Shape['* dim0, * dim1, * dim2'], Any] | NDArray[Shape['* dim0, * dim1, * dim2, * dim3'], Any] | None¶
- model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}¶
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'strict': False, 'use_enum_values': True, 'validate_assignment': True, 'validate_default': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'array': FieldInfo(annotation=Union[NDArray, NDArray, NDArray, NDArray, NoneType], required=False, default=None), 'description': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Description of what this table region points to.'), 'hdf5_path': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='The absolute path that this object is stored in an NWB file'), 'name': FieldInfo(annotation=str, required=True), 'object_id': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Unique UUID for each object'), 'table': FieldInfo(annotation=Union[DynamicTable, NoneType], required=False, default=None, description='Reference to the DynamicTable object that this region applies to.')}¶
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class ConfiguredBaseModel(*, hdf5_path: str | None = None, object_id: str | None = None)¶
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'strict': False, 'use_enum_values': True, 'validate_assignment': True, 'validate_default': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] = {}¶
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_fields: ClassVar[dict[str, FieldInfo]] = {'hdf5_path': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='The absolute path that this object is stored in an NWB file'), 'object_id': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Unique UUID for each object')}¶
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- class LinkMLMeta(root: RootModelRootType = PydanticUndefined)¶
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- model_config: ClassVar[ConfigDict] = {'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].