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

When using expand_vars=True, and the content is like "${VAR}ANOTHER_CONTENT", the ANOTHER_CONTENT will be ignored. #359

Open
flymanzhao opened this issue Oct 13, 2024 · 3 comments

Comments

@flymanzhao
Copy link

flymanzhao commented Oct 13, 2024

code

import os
os.environ["B"] = "${A};Val_B;"
os.environ["A"] = "Val_A"
from environs import Env
env = Env(expand_vars=True)
print(env("B"))

expect:

Val_A;Val_B;

what I got:

Val_A

is this a bug? Thanks very much!

@sloria
Copy link
Owner

sloria commented Oct 13, 2024

Hm, I'd also expect expanded variables to work with other characters included. Would def appreciate a PR if any kind soul looks into this

@basedBaba
Copy link

Hello! I am a first-time contributor to environs and new to open-source in general, so I apologize in advance if something I say does not make sense.

This bug seems to be caused by expand_match, which only matches and expands when the variable is present at the beginning and ignores the rest.

expand_match = self.expand_vars and _EXPANDED_VAR_PATTERN.match(value)
if expand_match: # Full match expand_vars - special case keep default
proxied_key: _StrType = expand_match.groups()[0]
subs_default: typing.Optional[_StrType] = expand_match.groups()[1]
if subs_default is not None:
default = subs_default[2:]
elif (
value == default
): # if we have used default, don't use it recursively
default = ma.missing
return (
key,
self._get_from_environ(proxied_key, default, proxied=True)[1],
proxied_key,
)

Meanwhile, expand_search along with _expand_vars seems to handle all cases, whether the variable is present at the beginning or in the middle, and also seems to handle default values as well.

expand_search = self.expand_vars and _EXPANDED_VAR_PATTERN.search(value)
if (
expand_search
): # Multiple or in text match expand_vars - General case - default lost
return self._expand_vars(env_key, value)

Using expand_search for all cases instead of expand_match seems to fix this particular bug, not sure if it breaks some other functionality.

Please let me know if this approach makes sense, so I can open a pull request for the same. Thank you!

@flymanzhao
Copy link
Author

Thanks @basedBaba , I also noticed this. I think you are correct. But I also want to point out that the r"$" is not handled correctly either. We'd better handle the var expansion and the r"$" replacement in one time.

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

3 participants