Fields¶
Field definitions for dotenvmodel configuration classes.
fields ¶
Field descriptor and Required sentinel for dotenvmodel.
Required
module-attribute
¶
Sentinel value marking a field as required.
Use this as a class attribute value instead of Field() when you want
to be explicit that a field is required. Functionally identical to
Field() with no arguments.
When to use
- When you prefer the explicit
Requiredsyntax overField() - For readability when a field has no constraints or defaults
Example
See Also
Field: For fields with defaults or constraints.
ValidatorContext
dataclass
¶
Context passed to a field's custom validator hook.
When to use
- Received as the second argument of any
Field(validator=...)callable; you never construct it yourself
Attributes:
| Name | Type | Description |
|---|---|---|
field_name |
str
|
The Python field name (e.g. |
env_var_name |
str
|
The resolved environment variable name, including any
|
Example
See Also
Field: For attaching a validator to a field.
FieldInfo ¶
FieldInfo(
default: Any = _MISSING,
*,
default_factory: Callable[[], Any] | None = None,
alias: str | None = None,
description: str | None = None,
ge: int | float | Decimal | None = None,
le: int | float | Decimal | None = None,
gt: int | float | Decimal | None = None,
lt: int | float | Decimal | None = None,
min_length: int | None = None,
max_length: int | None = None,
regex: str | None = None,
starts_with: str | None = None,
ends_with: str | None = None,
strip: bool | str | Pattern[str] | None = None,
choices: list[Any] | None = None,
validator: Callable[[Any, ValidatorContext], Any]
| None = None,
min_items: int | None = None,
max_items: int | None = None,
uuid_version: int | None = None,
separator: str = ",",
url_unquote: bool = True,
resolve_path: bool = True,
require_exists: bool = False,
)
Information about a configuration field.
This class holds all metadata about a field including its default value,
validation constraints, and documentation. You typically don't create
FieldInfo directly — use the Field() function instead.
When to use directly
- Rarely. Use
Field()in almost all cases. - When introspecting field metadata via
get_fields()
Attributes:
| Name | Type | Description |
|---|---|---|
default |
Any
|
Default value if env var not set (or |
default_factory |
Callable[[], Any] | None
|
Callable that returns a default value (for mutable defaults) |
alias |
str | None
|
Alternative environment variable name (overrides prefix) |
description |
str | None
|
Human-readable description for documentation |
ge |
int | float | Decimal | None
|
Greater-than-or-equal constraint (>=) |
le |
int | float | Decimal | None
|
Less-than-or-equal constraint (<=) |
gt |
int | float | Decimal | None
|
Greater-than constraint (>) |
lt |
int | float | Decimal | None
|
Less-than constraint (<) |
min_length |
int | None
|
Minimum string length |
max_length |
int | None
|
Maximum string length |
regex |
str | None
|
Regular expression pattern to match |
starts_with |
str | None
|
Required string prefix |
ends_with |
str | None
|
Required string suffix |
strip |
bool | str | Pattern[str] | None
|
Strip mode for string values (bool, char-set str, or re.Pattern) |
choices |
list[Any] | None
|
List of allowed values |
validator |
Callable[[Any, ValidatorContext], Any] | None
|
Custom validation/transformation hook |
before_validators |
list[_ValidatorHook]
|
|
after_validators |
list[_ValidatorHook]
|
|
min_items |
int | None
|
Minimum items in a collection |
max_items |
int | None
|
Maximum items in a collection |
uuid_version |
int | None
|
Required UUID version (1, 3, 4, or 5) |
separator |
str
|
Delimiter for parsing list/set/tuple/dict from string (default ",") |
url_unquote |
bool
|
Whether to URL-unquote SecretStr values (default True) |
required |
bool
|
Whether the field is required (computed from default) |
See Also
Field: The function you should use to create fields.
Source code in dotenvmodel/fields.py
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 | |
validator
instance-attribute
¶
get_default ¶
Get the default value for this field.
Literal defaults pass through smart_deepcopy so every load
receives an independent value: mutating one instance's default
cannot leak into other instances or future loads (pydantic parity).
Literal defaults must therefore be deep-copyable — a default
holding state copy.deepcopy cannot handle (a lock, a socket)
raises here; use default_factory for such values. Immutable
defaults are returned as-is. default_factory is invoked on
every load and its result is handed out as-is, never copied: if
the factory returns a shared object, that object stays shared.
Source code in dotenvmodel/fields.py
__repr__ ¶
Source code in dotenvmodel/fields.py
field_validator ¶
field_validator(
field_name: str,
/,
*,
mode: Literal["before", "after"] = "after",
) -> Callable[[_F], _F]
Register a method as a custom validation/transformation hook for one field.
Apply inside a DotEnvConfig subclass; the metaclass attaches the
decorated callable to the named field. The hook receives
(value, ctx) — the same contract as Field(validator=...) — and its
return value feeds the next pipeline stage.
When to use
- When the validation logic is too long to sit inline in
Field(...) - To attach several hooks to one field (stacking the decorator also registers one method for several fields)
- To normalize the raw external string before built-in
stripand type coercion (mode="before")
Supported callable forms (the receiver is detected from the first
positional parameter name):
- plain method: def hook(self, value, ctx) — bound to the instance
- @classmethod: def hook(cls, value, ctx) — bound to the class
- @staticmethod or module-level function: def hook(value, ctx) —
no receiver; a module-level function is decorated at module level
and assigned inside the class body
Modes
mode="after"(default): identical semantics toField(validator=...)— runs on the coerced, built-in-constraint-validated value, may transform it (built-ins are not re-run), never runs onNone, and runs even withvalidate=False. When both an inlineField(validator=...)and after-mode hooks exist, the inline hook runs first, then decorator hooks in definition order.mode="before": runs on the raw external value (the environment orload_from_dictstring) before built-instripand before type coercion, and may replace it — astrreturn re-enters the built-in strip and coercion, while a non-str return already typed as the field's declared type is used as-is (any other non-str return raisesTypeCoercionError). Not applied to field defaults (defaults are author-controlled values, not external input needing normalization). Also runs withvalidate=False.
Errors and secrets
A ValueError/TypeError raised by the hook is wrapped in
ConstraintViolationError (constraint="validator=<method name>")
in either mode; other exceptions propagate unchanged. For sensitive
fields (SecretStr, DSN types) any failure is masked generically —
including mode="before" hooks, which see the raw plaintext — so
the secret cannot leak through the hook's error text.
Inheritance
Hooks are inherited. Redefining a same-named method in a subclass
replaces that hook (redefining it without the decorator removes it);
the parent class's hooks are never affected. Hooks survive a field
being redeclared with a fresh Field(...).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_name
|
str
|
Name of the field the hook attaches to. The field must
exist (on this class or a base) at class definition time, or
class creation raises |
required |
mode
|
Literal['before', 'after']
|
When the hook runs — |
'after'
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Example
import logging
from dotenvmodel import DotEnvConfig, Field, ValidatorContext, field_validator
class AppConfig(DotEnvConfig):
log_level: str = Field(default="ERROR", strip=True)
@field_validator("log_level", mode="before")
def uppercase_log_level(self, value: str, ctx: ValidatorContext) -> str:
return value.upper()
@field_validator("log_level")
def convert_to_logging_int(self, value: str, ctx: ValidatorContext) -> int:
return logging.getLevelNamesMapping().get(value, logging.ERROR)
See Also
Field: The inline single-hook form viavalidator=.ValidatorContext: The context argument every hook receives.
Source code in dotenvmodel/fields.py
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | |
smart_deepcopy ¶
Return a value safe to hand out as a per-load default.
Values whose exact type is immutable (None, bool, int,
float, complex, str, bytes, range, dates/times,
timedelta, Decimal, UUID, SecretStr, BaseDsn) are
returned as-is at zero cost. Empty list/dict/set values get
a shallow copy() — they hold nothing that could be shared.
Everything else — non-empty or possibly nested containers, subclasses
(which can carry mutable state), custom objects — is
copy.deepcopy-ed; singletons such as Enum members come back
from deepcopy as the same object.
This mirrors pydantic's smart_deepcopy (exact-type membership) so
that a literal mutable default such as Field(default=["localhost"])
is isolated per load() call instead of being shared — and mutated —
across every instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The literal default value to copy. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The same object for exact-type immutable values, otherwise an |
Any
|
independent copy. |
Source code in dotenvmodel/fields.py
Field ¶
Field(
default: Any = _MISSING,
*,
default_factory: Callable[[], Any] | None = None,
alias: str | None = None,
description: str | None = None,
ge: int | float | Decimal | None = None,
le: int | float | Decimal | None = None,
gt: int | float | Decimal | None = None,
lt: int | float | Decimal | None = None,
min_length: int | None = None,
max_length: int | None = None,
regex: str | None = None,
starts_with: str | None = None,
ends_with: str | None = None,
strip: bool | str | Pattern[str] | None = None,
choices: list[Any] | None = None,
validator: Callable[[Any, ValidatorContext], Any]
| None = None,
min_items: int | None = None,
max_items: int | None = None,
uuid_version: int | None = None,
separator: str = ",",
url_unquote: bool = True,
resolve_path: bool = True,
require_exists: bool = False,
) -> Any
Define a configuration field with validation and default values.
When to use
- Always use
Field()(orRequired) to define config fields - Use
Field()with no arguments for a required string field - Use
Field(...)(ellipsis) for any required field — Pydantic-style - Use
Field(default=value)for optional fields with defaults
When to use default vs default_factory:
- Use default for immutable values (str, int, float, bool, None).
Literal defaults must be deep-copyable (each load deep-copies
them); use default_factory for values that are not
- Mutable default values (list, dict, set) are safe — each load
deep-copies them — but default_factory avoids that per-load
copy cost
- default_factory is invoked on every load and its result is
handed out as-is, never copied — construct new values inside
the factory; a factory returning a shared object keeps it shared
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
Any
|
Default value if environment variable not set. Use |
_MISSING
|
default_factory
|
Callable[[], Any] | None
|
Callable that returns a default value. Prefer this over a
mutable |
None
|
alias
|
str | None
|
Alternative environment variable name to read from. When set, the
field name is not used for env var lookup, and |
None
|
description
|
str | None
|
Human-readable description shown in |
None
|
ge
|
int | float | Decimal | None
|
Greater than or equal to (>=). For int, float, and Decimal fields.
Example: |
None
|
le
|
int | float | Decimal | None
|
Less than or equal to (<=). For int, float, and Decimal fields.
Example: |
None
|
gt
|
int | float | Decimal | None
|
Greater than (>). For int, float, and Decimal fields.
Example: |
None
|
lt
|
int | float | Decimal | None
|
Less than (<). For int, float, and Decimal fields.
Example: |
None
|
min_length
|
int | None
|
Minimum string length (inclusive). For str and SecretStr fields.
Example: |
None
|
max_length
|
int | None
|
Maximum string length (inclusive). For str and SecretStr fields.
Example: |
None
|
regex
|
str | None
|
Regular expression pattern the string must match (using |
None
|
starts_with
|
str | None
|
Required string prefix. For str and str subclasses (including
SecretStr and DSN types like HttpUrl, PostgresDsn, RedisDsn).
Example: |
None
|
ends_with
|
str | None
|
Required string suffix. For str and str subclasses (including
SecretStr and DSN types like HttpUrl, PostgresDsn, RedisDsn).
Example: |
None
|
strip
|
bool | str | Pattern[str] | None
|
Strip mode applied to the raw string before coercion. Applies to str, SecretStr, their Optional forms, and str subclasses (e.g. HttpUrl):
Example: |
None
|
choices
|
list[Any] | None
|
List of allowed values. The env var value must be in this list
(after type coercion). Example: |
None
|
validator
|
Callable[[Any, ValidatorContext], Any] | None
|
Custom hook called with the coerced, built-in-constraint-validated
value and a |
None
|
min_items
|
int | None
|
Minimum number of items in a collection (list, set, tuple, dict).
Example: |
None
|
max_items
|
int | None
|
Maximum number of items in a collection (list, set, tuple, dict).
Example: |
None
|
uuid_version
|
int | None
|
Required UUID version (1, 3, 4, or 5). For UUID fields.
Example: |
None
|
separator
|
str
|
Delimiter for parsing list/set/tuple/dict from a string.
Default is comma (","). Example: |
','
|
url_unquote
|
bool
|
Whether to URL-unquote SecretStr values (default True). Useful when secrets come from URL-encoded env vars. |
True
|
resolve_path
|
bool
|
Whether to resolve Path values (expanduser + resolve). Default True. Set to False to keep paths raw. |
True
|
require_exists
|
bool
|
Whether a Path field must point to an existing path. Default False. |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
FieldInfo instance containing field metadata. Used by the |
Any
|
metaclass to discover and process fields. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If both |
TypeError
|
If numeric constraints ( |
Example
class Config(DotEnvConfig):
# Required field (no default)
database_url: str = Field()
# Required field (Pydantic-style with ellipsis)
api_key: str = Field(...)
# Optional with default
debug: bool = Field(default=False)
# With validation
port: int = Field(default=8000, ge=1, le=65535)
# With alias (overrides env_prefix)
postgres_dsn: str = Field(alias="DATABASE_URL")
# Mutable default with default_factory
hosts: list[str] = Field(default_factory=list)
# List with custom separator
tags: list[str] = Field(default_factory=list, separator=";")
# Collection size constraints
allowed_ips: list[str] = Field(min_items=1, max_items=10)
# UUID version constraint
tenant_id: UUID = Field(uuid_version=4)
# Choice validation
env: str = Field(default="dev", choices=["dev", "test", "prod"])
# SecretStr with length constraint
api_key: SecretStr = Field(min_length=32)
# Strip whitespace from the raw value before coercion
name: str = Field(strip=True)
# Char-set and regex strip modes
tag: str = Field(strip=",'"") # str.strip(chars) semantics
key: str = Field(strip=re.compile(r"^['"]+|['"]+$")) # remove every match
# Prefix/suffix constraints
client_key: str = Field(starts_with="sk-")
signed_token: str = Field(ends_with=".sig")
# Custom validator (may also transform the value)
region: str = Field(default="us-east-1", validator=lambda v, ctx: v.lower())
See Also
Required: Sentinel for required fields.FieldInfo: The class returned byField().field_validator: Decorator form for attaching hooks by field name, with before/after modes.
Source code in dotenvmodel/fields.py
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 | |