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

Error when parsing empty list with subcast #137

Closed
sabdouni opened this issue Feb 19, 2020 · 4 comments
Closed

Error when parsing empty list with subcast #137

sabdouni opened this issue Feb 19, 2020 · 4 comments

Comments

@sabdouni
Copy link
Contributor

Hello,

The env.list can't handle an empty list when using subcast
It raises an exception environs.EnvValidationError: Environment variable "LIST" invalid: {0: ['Not a valid integer.']}
This can be reproduced by e.g

    os.environ["LIST"] = ""
    env = Env()
    LIST = env.list("LIST", [], subcast=int)

If you don't use subcast it works just fine by e.g

    os.environ["LIST"] = ""
    env = Env()
    LIST = env.list("LIST", [])

Maybe one solution is if the env variable is falsy (empty or doesn't exist) env.list should return the default value if defined

Happy to submit a PR if that would be of interest. Thanks!

@sloria
Copy link
Owner

sloria commented Feb 20, 2020

Thanks for reporting. PRs welcome! =)

@sabdouni
Copy link
Contributor Author

sabdouni commented Mar 5, 2020

@sloria
The bug is located in the method _preprocess_list and is not really related to environs code but to a really weird behavior of 'split' see here

I have a fix :

  • Refactor _preprocess_list to this :
def _preprocess_list(value: typing.Union[str, typing.Iterable], **kwargs) -> typing.Iterable:
    if ma.utils.is_iterable_but_not_string(value):
        return value
    return typing.cast(str, value).split(",") if value != "" else []
  • And add this unit test :
    def test_list_with_empty_env_and_subcast(self, set_env, env):
        set_env({"LIST": ""})
        assert env.list("LIST", subcast=int) == []
        assert env.list("LIST", subcast=float) == []

What do you think ?

@sloria
Copy link
Owner

sloria commented Mar 5, 2020

Seems like a reasonable fix

@sloria
Copy link
Owner

sloria commented Mar 22, 2020

Fix is released in 7.3.1

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

No branches or pull requests

2 participants