'Is it safe to define a context manager around a nested function?

For a third party library* I have to provide a function which consumes some data. My implementation of the consumption requires the data to be posted to an API. So I came up with this structure below:

def consumer_provider():

    with HttpClient() as http_client:
        
        def consumer(data):
            http_client.post(data)

        return consumer

So I can present the function to the third party lib like so:

third_party_lib.add(consumer=consumer_provider())

In my tests it works quite well, but is this legit? When do I have to expect that the context manager releases the resource (in this case the connection pool)?

* loguru in this case, but it should not really matter for the question



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source