python-dotenv icon indicating copy to clipboard operation
python-dotenv copied to clipboard

Feature Request: Unloading function unload_dotenv()

Open nobites opened this issue 1 month ago • 3 comments

Once load_dotenv() has run, variables are set. To remove them again for unit testing, I need a function, because tests should be independent. I coded this function already, but I think it would be nice to have it included in dotenv. I guess, I'm not the only one with the described problem. But maybe I'm wrong. I stepped over this more than once now. That's why I'm suggesting adding this function:

def unload_dotenv():
    """Remove all dotenv variables from environment."""

    dotenv_vars = set(dotenv_values().keys())
    for key in dotenv_vars:
        os.environ.pop(key, None)

nobites avatar Nov 28 '25 08:11 nobites

If you encountered this problem in unit testing, perhaps you will be interested in unittest.mock.patch.dict. Check out how it is used in the UTs of this package https://github.com/theskumar/python-dotenv/blob/main/tests/test_main.py#L326 for mocking os.environ

As you see unload_dotenv is quite easy to write if that is the behaviour you want to achieve. I see a problem, that users may expect many different behaviours from a function called unload_dotenv. For example if one use it with override=True, they may expect the library to bring back the state of environment from before the load_dotenv call. Another example would be setting a variable via load_dotenv and then changing it by other means, in such cases users may expect unload_dotenv will not unload the variable. I think this kind of functions are very project specific and perhaps should be implemented on the project side.

Bajron avatar Dec 01 '25 19:12 Bajron

@Bajron - I know mocking. But there is a good reason why I requested an unload function. Especially in complex integration tests. I don't stick to the name of the suggested function, but to its functionality. If you provide a load_dotenv() that loads variables from an .env file, there should also be a way to unload this again. Don't you think so?

nobites avatar Dec 04 '25 13:12 nobites

I see load_dotenv more like a facility to prepare the environment and just that.

I think unload_dotenv could be confusing. It suggests the .env file or this library owns certain environment variables, but it is not really the case. In my experience, operations on global state are rarely that simple.

Your use case may show a certain need in the prepare environment scenario though. Sometimes we want to unset a variable, so it is not present in the environment. Some applications may handle missing and empty string state of an environment variable differently. It would be nice if this library could handle the unset keyword. It handles export already so it shouldn't be a big deal I guess.

Bajron avatar Dec 04 '25 19:12 Bajron