Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default values defined in casted types #297

Open
lucas-bremond opened this issue Aug 22, 2023 · 4 comments
Open

Default values defined in casted types #297

lucas-bremond opened this issue Aug 22, 2023 · 4 comments

Comments

@lucas-bremond
Copy link

lucas-bremond commented Aug 22, 2023

Before I submit a PR, would the maintainer be open to allowing the following construct?

ttl = env.timedelta("TTL", default=600)  # Currently works
ttl = env.timedelta("TTL", default=timedelta(minutes=10))  # Raises `environs.EnvValidationError`

The concept could be extended to other types, too: i.e., when the default value is provided in the already casted/output type, then use it as-is.

I think it'd make the interface nicer because expressing durations (for instance) only in seconds is less declarative than using a natural timedelta construct (especially when dealing with more complex durations).

Thoughts?

@fdemmer
Copy link

fdemmer commented Jan 16, 2024

related: #270

@boyleconnor
Copy link

This would be especially useful for enums. E.g.:

from environs import Env

env = Env()
env.read_env()

class DataSource(enum.Enum):
    # Possible places from which to mount a data bucket to the inference containers:
    s3 = "s3"
    kubernetes_filesystem = "kubernetes-filesystem"

# This works
DATA_SOURCE: DataSource = env.enum("DATA_SOURCE",DataSource.kubernetes_filesystem.name, type=InferenceDataBucketSource)

# This does not work, but it would if this feature request were implemented
DATA_SOURCE: DataSource = env.enum("DATA_SOURCE",DataSource.kubernetes_filesystem, type=InferenceDataBucketSource)

# Pitfall, do NOT do this:
# This will work when the `name` of an Enum value happens to be the same as its `value`, which is true for _some_, but not all, of the values of this Enum (and many others).
DATA_SOURCE: DataSource = env.enum("DATA_SOURCE",DataSource.kubernetes_filesystem.value, type=InferenceDataBucketSource)

@ddelange
Copy link
Contributor

for timedelta specifically, support for passing a timedelta object as default argument was added in #366

@ddelange
Copy link
Contributor

ddelange commented Nov 21, 2024

for future reference leaving this bug here.

float as default is silently downcast to int by marshmallow. float-as-string is correctly rejected by marshmallow (see further below in this test):

https://github.com/sloria/environs/blob/11.2.1/tests/test_environs.py#L235

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants