dataclass_wizard.environ package¶
Submodules¶
dataclass_wizard.environ.dumpers module¶
- dataclass_wizard.environ.dumpers.asdict(o, *, cls=None, dict_factory=<class 'dict'>, exclude=None, **kwargs)[source]¶
Return the fields of an instance of a EnvWizard subclass as a new dictionary mapping field names to field values.
Example usage:
class MyEnv(EnvWizard): x: int y: str env = MyEnv() serialized = asdict(env)
When directly invoking this function, an optional Meta configuration for the EnvWizard subclass can be specified via
EnvMeta
; by default, this will apply recursively to any nested subclasses. Here’s a sample usage of this below:>>> EnvMeta(key_transform_with_dump='CAMEL').bind_to(MyClass) >>> asdict(MyClass(my_str="value"))
If given, ‘dict_factory’ will be used instead of built-in dict. The function applies recursively to field values that are EnvWizard subclasses. This will also look into built-in containers: tuples, lists, and dicts.
- Return type:
dict
[str
,Any
]- Parameters:
o (T)
exclude (Collection[str] | None)
dataclass_wizard.environ.loaders module¶
- class dataclass_wizard.environ.loaders.EnvLoader[source]¶
Bases:
LoadMixin
This Mixin class derives its name from the eponymous json.loads function. Essentially it contains helper methods to convert JSON strings (or a Python dictionary object) to a dataclass which can often contain complex types such as lists, dicts, or even other dataclasses nested within it.
Refer to the
AbstractLoader
class for documentation on any of the implemented methods.- static load_func_for_dataclass(cls, config, is_main_class=False)[source]¶
- Return type:
Callable
[[Union
[str
,dict
[str
,Any
],TypeVar
(T
)],Type
[TypeVar
(T
)]],TypeVar
(T
)]- Parameters:
cls (Type[T])
config (Type[META_] | None)
is_main_class (bool)
- static load_to_byte_array(o, base_type, encoding='utf-8')[source]¶
- Return type:
bytearray
- Parameters:
o (AnyStr)
base_type (Type[bytearray])
- static load_to_bytes(o, base_type, encoding='utf-8')[source]¶
- Return type:
bytes
- Parameters:
o (AnyStr)
base_type (Type[bytes])
- static load_to_date(o, base_type)[source]¶
Attempt to convert an object o to a
date
object using the below logic. :rtype:date
str
: convert date strings (in ISO format) via the built-infromisoformat
method.Number
(int or float): Convert a numeric timestamp via thebuilt-in
fromtimestamp
method.
date
: Return object o if it’s already of this type orsub-type.
Otherwise, if we’re unable to convert the value of o to a
date
as expected, raise an error if the raise_ parameter is true; if not, return default instead.- Parameters:
o (str | int | float)
base_type (Type[date])
- Return type:
date
- static load_to_datetime(o, base_type)[source]¶
Attempt to convert an object o to a
datetime
object using the below logic. :rtype:datetime
str
: convert datetime strings (in ISO format) via the built-infromisoformat
method.Number
(int or float): Convert a numeric timestamp via thebuilt-in
fromtimestamp
method, and return a UTC datetime.
datetime
: Return object o if it’s already of this type orsub-type.
Otherwise, if we’re unable to convert the value of o to a
datetime
as expected, raise an error if the raise_ parameter is true; if not, return default instead.- Parameters:
o (str | int | float)
base_type (Type[datetime])
- Return type:
datetime
- static load_to_defaultdict(o, base_type, default_factory, key_parser, val_parser)[source]¶
- Return type:
TypeVar
(DD
, bound=defaultdict
)- Parameters:
o (Dict)
base_type (Type[DD])
default_factory (Callable[[], T])
key_parser (AbstractParser)
val_parser (AbstractParser)
- static load_to_dict(o, base_type, key_parser, val_parser)[source]¶
- Return type:
TypeVar
(M
, bound=Mapping
)- Parameters:
o (Dict)
base_type (Type[M])
key_parser (AbstractParser)
val_parser (AbstractParser)
- static load_to_iterable(o, base_type, elem_parser)[source]¶
- Return type:
TypeVar
(LSQ
,list
,set
,frozenset
,deque
)- Parameters:
o (Iterable)
base_type (Type[LSQ])
elem_parser (AbstractParser)
- static load_to_named_tuple(o, base_type, field_to_parser, field_parsers)[source]¶
- Return type:
TypeVar
(NT
, bound=NamedTuple
)- Parameters:
o (Dict | List | Tuple)
base_type (Type[NT])
field_to_parser (FieldToParser)
field_parsers (List[AbstractParser])
- static load_to_named_tuple_untyped(o, base_type, dict_parser, list_parser)[source]¶
- Return type:
TypeVar
(NT
, bound=NamedTuple
)- Parameters:
o (Dict | List | Tuple)
base_type (Type[NT])
dict_parser (AbstractParser)
list_parser (AbstractParser)
- static load_to_tuple(o, base_type, elem_parsers)[source]¶
- Return type:
Tuple
- Parameters:
o (List | Tuple)
base_type (Type[Tuple])
elem_parsers (Sequence[AbstractParser])
dataclass_wizard.environ.lookups module¶
- class dataclass_wizard.environ.lookups.Env[source]¶
Bases:
object
- cleaned_to_env = {}¶
- classmethod dotenv_values(files)[source]¶
Retrieve the values (environment variables) from a dotenv file, or a list/tuple of dotenv files.
- classmethod load_environ(force_reload=False)[source]¶
Load
environ
fromos.environ
.If force_reload is true, start fresh and re-copy os.environ.
- classmethod secret_values(dirs)[source]¶
Retrieve the values (environment variables) from secret file(s) in a secret directory, or a list/tuple of secret directories.
- var_names = {}¶
- dataclass_wizard.environ.lookups.clean(s)[source]¶
- TODO:
see https://stackoverflow.com/questions/1276764/stripping-everything-but-alphanumeric-chars-from-a-string-in-python also, see if we can refactor to use something like Rust and pyo3 for a slight performance improvement.
- dataclass_wizard.environ.lookups.lookup_exact(var)[source]¶
Lookup by variable name(s) with exact letter casing, and return None if not found in the environment.
- dataclass_wizard.environ.lookups.try_cleaned(key)[source]¶
Return the value of the env variable as a string if present in the Environment, or MISSING otherwise.
- dataclass_wizard.environ.lookups.with_pascal_or_camel_case(field_name)[source]¶
Lookup with PascalCase or camelCase letter casing first.
This function assumes the dataclass field name is either pascal- or camel- cased.
- For a field named ‘myEnvVar’, this tries the following lookups in order:
myEnvVar, MyEnvVar (camel-case, or pascal-case)
MY_ENV_VAR (screaming snake-case)
my_env_var (snake-case)
Any other variations - i.e. my-env-var, myenvvar
- Parameters:
field_name – The dataclass field name to lookup in the environment.
- Returns:
The value of the matched environment variable, if one is found in the environment.
- dataclass_wizard.environ.lookups.with_screaming_snake_case(field_name)[source]¶
Lookup with SCREAMING_SNAKE_CASE letter casing first - this is the default lookup.
This function assumes the dataclass field name is lower-cased.
- For a field named ‘my_env_var’, this tries the following lookups in order:
MY_ENV_VAR (screaming snake-case)
my_env_var (snake-case)
Any other variations - i.e. MyEnvVar, myEnvVar, myenvvar, my-env-var
- Parameters:
field_name – The dataclass field name to lookup in the environment.
- Returns:
The value of the matched environment variable, if one is found in the environment.
- dataclass_wizard.environ.lookups.with_snake_case(field_name)[source]¶
Lookup with snake_case letter casing first.
This function assumes the dataclass field name is lower-cased.
- For a field named ‘my_env_var’, this tries the following lookups in order:
my_env_var (snake-case)
MY_ENV_VAR (screaming snake-case)
Any other variations - i.e. MyEnvVar, myEnvVar, myenvvar, my-env-var
- Parameters:
field_name – The dataclass field name to lookup in the environment.
- Returns:
The value of the matched environment variable, if one is found in the environment.
dataclass_wizard.environ.wizard module¶
- class dataclass_wizard.environ.wizard.EnvWizard[source]¶
Bases:
AbstractEnvWizard
Environment Wizard
A mixin class for parsing and managing environment variables in Python.
EnvWizard
makes it easy to map environment variables to Python attributes, handle defaults, and optionally load values from .env files.Quick Example:
import os from pathlib import Path class MyConfig(EnvWizard): my_var: str my_optional_var: int = 42 # Set environment variables os.environ["MY_VAR"] = "hello" # Load configuration from the environment config = MyConfig() print(config.my_var) # Output: "hello" print(config.my_optional_var) # Output: 42 # Specify configuration explicitly config = MyConfig(my_var='world') print(config.my_var) # Output: "world" print(config.my_optional_var) # Output: 42
Example with
.env
file:class MyConfigWithEnvFile(EnvWizard): class _(EnvWizard.Meta): env_file = True # Defaults to loading from `.env` my_var: str my_optional_var: int = 42 # Create an `.env` file in the current directory: # MY_VAR=world config = MyConfigWithEnvFile() print(config.my_var) # Output: "world" print(config.my_optional_var) # Output: 42
- Key Features:
Automatically maps environment variables to dataclass fields.
Supports default values for fields if environment variables are not set.
Optionally loads environment variables from .env files.
Supports prefixes for environment variables using
_env_prefix
orMeta.env_prefix
.Supports loading secrets from directories using
_secrets_dir
orMeta.secrets_dir
.Dynamic reloading with
_reload
to handle updated environment values.
- Initialization Options:
The
__init__
method accepts additional parameters for flexibility:_env_file
(optional):Overrides the
Meta.env_file
value dynamically. Can be a file path, a sequence of file paths, orTrue
to use the default .env file.
_reload
(optional):Forces a reload of environment variables to bypass caching. Defaults to
False
.
_env_prefix
(optional):Dynamically overrides
Meta.env_prefix
, applying a prefix to all environment variables. Defaults toNone
.
_secrets_dir
(optional):Overrides the
Meta.secrets_dir
value dynamically. Can be a directory path or a sequence of paths pointing to directories containing secret files.
- Meta Settings:
These class-level attributes can be configured in a nested
Meta
class:env_file
:The path(s) to .env files to load. If set to
True
, defaults to .env.
env_prefix
:A prefix applied to all environment variables. Defaults to
None
.
secrets_dir
:A path or sequence of paths to directories containing secret files. Defaults to
None
.
- Attributes:
Defined dynamically based on the dataclass fields in the derived class.
- class Meta[source]¶
Bases:
BaseEnvWizardMeta
Inner meta class that can be extended by sub-classes for additional customization with the environment load process.
- to_dict(*, cls=None, dict_factory=<class 'dict'>, exclude=None, **kwargs)¶
Return the fields of an instance of a EnvWizard subclass as a new dictionary mapping field names to field values.
Example usage:
class MyEnv(EnvWizard): x: int y: str env = MyEnv() serialized = asdict(env)
When directly invoking this function, an optional Meta configuration for the EnvWizard subclass can be specified via
EnvMeta
; by default, this will apply recursively to any nested subclasses. Here’s a sample usage of this below:>>> EnvMeta(key_transform_with_dump='CAMEL').bind_to(MyClass) >>> asdict(MyClass(my_str="value"))
If given, ‘dict_factory’ will be used instead of built-in dict. The function applies recursively to field values that are EnvWizard subclasses. This will also look into built-in containers: tuples, lists, and dicts.
- Return type:
dict
[str
,Any
]- Parameters:
o (T)
exclude (Collection[str] | None)