Types¶
Special types provided by dotenvmodel for advanced configuration scenarios.
types ¶
Special types for dotenvmodel.
SecretStr ¶
A string type that hides its value in logs and repr output.
Use this for sensitive data like API keys, passwords, and tokens to prevent them from appearing in logs, error messages, or debugging output.
When to use
- For API keys, passwords, tokens, and other secrets
- When config values might be logged or printed
- When you want to prevent accidental secret exposure in repr/str
When NOT to use
- For non-sensitive values (use
strinstead) - When you need to pickle the value (SecretStr prevents pickling for security)
Security features
- Hidden in str/repr output (shows
**********) - Name-mangled attribute to prevent accidental access
- Prevents pickling to avoid serialization leaks
- Immutable to prevent modification after creation
Example
See Also
Field: For defining SecretStr fields with constraints.
Source code in dotenvmodel/types.py
BaseDsn ¶
Bases: str
Base class for DSN (Data Source Name) types.
This base class provides common URL validation and parsing functionality
that can be extended by specific DSN types. You typically don't use this
directly — use HttpUrl, PostgresDsn, or RedisDsn instead.
When to subclass
- When you need a custom DSN type with specific scheme validation
- When you need parsed URL components as properties
Class Attributes
allowed_schemes: Tuple of allowed URL schemes (e.g., ("http", "https")) require_host: Whether the URL must have a host/netloc component (default True) default_port: Default port number when not specified in the URL
Properties
parsed: The urllib.parse.ParseResult for the URL
scheme: URL scheme (e.g., "https")
host: URL hostname
port: URL port number (or default_port if not specified)
path: URL path
query: URL query string
username: URL username (or None)
password: URL password, URL-decoded (or None)
See Also
HttpUrl: For HTTP/HTTPS URLs.PostgresDsn: For PostgreSQL DSNs.RedisDsn: For Redis DSNs.
__new__ ¶
Validate and create DSN instance.
Source code in dotenvmodel/types.py
__repr__ ¶
Return a redacted repr with any password masked.
Only repr is overridden. str(dsn) and the raw buffer remain the
real connection string so the DSN stays usable with database drivers
(create_engine(str(url)), redis.from_url(str(url)), etc.). This
masks the accidental-display path (repr(config), debuggers, %r
logging) without breaking functionality. Values that must never appear
in serialized output (json.dumps, .encode()) should use
SecretStr instead.
Source code in dotenvmodel/types.py
HttpUrl ¶
Bases: BaseDsn
A URL type that validates HTTP/HTTPS URLs.
Validates that the URL has a valid format and uses http or https scheme. Works like a string but provides parsed URL components as properties.
When to use
- For API endpoint URLs
- For web service URLs
- When you need to access URL components (host, port, path)
Allowed schemes: http, https
Default port: None (uses port from URL or protocol default)
Example
class Config(DotEnvConfig):
api_url: HttpUrl = Field()
# Environment: API_URL=https://api.example.com/v1
config = Config.load()
print(config.api_url) # https://api.example.com/v1
print(config.api_url.host) # api.example.com
print(config.api_url.port) # None (no explicit port)
print(config.api_url.path) # /v1
See Also
BaseDsn: Base class with all properties.PostgresDsn: For PostgreSQL DSNs.RedisDsn: For Redis DSNs.
PostgresDsn ¶
Bases: BaseDsn
A DSN type for PostgreSQL database URLs.
Validates that the URL follows PostgreSQL connection string format.
Accepts both postgresql:// and postgres:// schemes.
Default port is 5432 if not specified in the URL.
When to use
- For PostgreSQL connection strings
- When you need to extract database name, username, or password
Allowed schemes: postgresql, postgres
Default port: 5432
Additional Properties
database: Database name extracted from the URL path
Example
class Config(DotEnvConfig):
database_url: PostgresDsn = Field()
# Environment: DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
config = Config.load()
print(config.database_url.host) # localhost
print(config.database_url.port) # 5432
print(config.database_url.database) # mydb
print(config.database_url.username) # user
print(config.database_url.password) # pass (URL-decoded)
RedisDsn ¶
Bases: BaseDsn
A DSN type for Redis URLs.
Validates that the URL follows Redis connection string format.
Accepts both redis:// and rediss:// (SSL) schemes.
Default port is 6379 if not specified in the URL.
When to use
- For Redis connection strings
- When you need to extract the database number
Allowed schemes: redis, rediss (SSL)
Default port: 6379
Additional Properties
database: Redis database number extracted from the URL path (default 0)
Example
See Also
BaseDsn: Base class with all properties.PostgresDsn: For PostgreSQL DSNs.
Json ¶
A type for parsing JSON strings into Python objects.
Use this for complex configuration that needs to be passed as JSON. The inner type parameter is used for documentation and basic type validation.
When to use
- For feature flags stored as JSON objects
- For lists of complex values
- When a config value is naturally a JSON structure
When NOT to use
- For simple values (use str, int, bool, etc.)
- For comma-separated lists (use
list[str]with separator)
Type Validation
Json[dict]validates that the parsed result is a dictJson[list]validates that the parsed result is a list- Other inner types are accepted but not deeply validated
Example
class Config(DotEnvConfig):
# JSON object
feature_flags: Json[dict[str, bool]] = Field()
# Environment: FEATURE_FLAGS={"new_ui": true, "beta_api": false}
# JSON array
allowed_roles: Json[list[str]] = Field()
# Environment: ALLOWED_ROLES=["admin", "user", "guest"]
# JSON without type validation
raw_config: Json = Field()
# Environment: RAW_CONFIG={"nested": {"value": 42}}
config = Config.load()
assert config.feature_flags == {"new_ui": True, "beta_api": False}
assert config.allowed_roles == ["admin", "user", "guest"]
See Also
Field: For defining Json fields.
is_sensitive_type ¶
True when the (Optional-unwrapped) declared type holds a sensitive value.
A field is sensitive when its Optional/Union-unwrapped type is
SecretStr or a BaseDsn subclass (e.g. HttpUrl, PostgresDsn,
RedisDsn). Masking decisions in config.py use this on the declared
type rather than isinstance(value, ...) so a default-path value that
has not yet been wrapped cannot bypass redaction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tp
|
TypeForm[Any]
|
The field's type annotation |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the field is declared as a sensitive type |
Source code in dotenvmodel/types.py
is_sensitive_value ¶
True when value is a SecretStr or BaseDsn instance.
Such values mask themselves in repr (SecretStr shows
**********; BaseDsn redacts any URL password), so they are safe to
embed directly in error messages.
Source code in dotenvmodel/types.py
parse_timedelta ¶
Parse a human-readable duration string into a timedelta.
When to use
- Called automatically when a field is typed as
timedelta - Can be called directly for parsing durations outside of config
Supports formats like
- Plain integers: "90" (seconds)
- With units: "1h30m", "90s", "1.5h", "2d"
- Combined: "1d2h30m"
Units (case-insensitive): - ms: milliseconds - s: seconds - m: minutes - h: hours - d: days - w: weeks
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
Duration string (e.g., "90", "1h30m", "2d") |
required |
Returns:
| Type | Description |
|---|---|
timedelta
|
timedelta object representing the parsed duration |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the format is invalid |
Example
parse_timedelta("90") timedelta(seconds=90) parse_timedelta("1h30m") timedelta(seconds=5400) parse_timedelta("2d") timedelta(days=2) parse_timedelta("500ms") timedelta(milliseconds=500)
See Also
coerce_timedelta: Wrapper that raisesTypeCoercionErrorinstead ofValueError.
Source code in dotenvmodel/types.py
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 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 | |
coerce_datetime ¶
Coerce a string to datetime using ISO 8601 format.
When to use
- Called automatically when a field is typed as
datetime - Can be called directly for parsing outside of config
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
ISO 8601 datetime string |
required |
field_name
|
str
|
Field name for error messages |
required |
env_var_name
|
str
|
Environment variable name for error messages |
required |
Returns:
| Type | Description |
|---|---|
datetime
|
datetime object |
Raises:
| Type | Description |
|---|---|
TypeCoercionError
|
If parsing fails |
Source code in dotenvmodel/types.py
coerce_timedelta ¶
Coerce a string to timedelta.
When to use
- Called automatically when a field is typed as
timedelta - Can be called directly for parsing outside of config
Supports
- Plain integers: "90" (seconds)
- Human-readable: "1h30m", "90s", "2d"
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
Duration string |
required |
field_name
|
str
|
Field name for error messages |
required |
env_var_name
|
str
|
Environment variable name for error messages |
required |
Returns:
| Type | Description |
|---|---|
timedelta
|
timedelta object |
Raises:
| Type | Description |
|---|---|
TypeCoercionError
|
If parsing fails |
Source code in dotenvmodel/types.py
coerce_uuid ¶
Coerce a string to UUID.
When to use
- Called automatically when a field is typed as
UUID - Can be called directly for parsing outside of config
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
UUID string (with or without hyphens) |
required |
field_name
|
str
|
Field name for error messages |
required |
env_var_name
|
str
|
Environment variable name for error messages |
required |
Returns:
| Type | Description |
|---|---|
UUID
|
UUID object |
Raises:
| Type | Description |
|---|---|
TypeCoercionError
|
If parsing fails |
Source code in dotenvmodel/types.py
coerce_decimal ¶
Coerce a string to Decimal.
When to use
- Called automatically when a field is typed as
Decimal - Can be called directly for parsing outside of config
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
Numeric string |
required |
field_name
|
str
|
Field name for error messages |
required |
env_var_name
|
str
|
Environment variable name for error messages |
required |
Returns:
| Type | Description |
|---|---|
Decimal
|
Decimal object |
Raises:
| Type | Description |
|---|---|
TypeCoercionError
|
If parsing fails |
Source code in dotenvmodel/types.py
coerce_json ¶
coerce_json(
value: str,
field_name: str,
env_var_name: str,
expected_type: type[T] | None = None,
) -> T
Parse JSON string and optionally validate against expected type.
When to use
- Called automatically when a field is typed as
Json[T] - Can be called directly for parsing JSON outside of config
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
JSON string |
required |
field_name
|
str
|
Field name for error messages |
required |
env_var_name
|
str
|
Environment variable name for error messages |
required |
expected_type
|
type[T] | None
|
Optional type to validate against |
None
|
Returns:
| Type | Description |
|---|---|
T
|
Parsed JSON object |
Raises:
| Type | Description |
|---|---|
TypeCoercionError
|
If parsing fails or type doesn't match |