Skip to content

Instantly share code, notes, and snippets.

@abetkin
Last active November 4, 2016 12:39
Show Gist options
  • Save abetkin/0061c1e8ae7998c1b2194a737373388f to your computer and use it in GitHub Desktop.
Save abetkin/0061c1e8ae7998c1b2194a737373388f to your computer and use it in GitHub Desktop.

Hi everyone!

I am coming from Python background, and in Python we have context managers.

These are objects encapsulating the try-catch-finally block, and usually are used to cleanup resources, like closing the open file. In Python community, most developers consider context managers a very neat feature of the language and you really can find them often in the code.

So, my question is: why is this feature missing completely in the js world? I could not find a single library. I think I can imagine what it could look like:

import With from 'missing-context-managers'
import open from 'some-file-utils'

With(open(file_path), (file) => {
    // file is open now
    console.log(file.getContents())
})
// file is closed now

From what I understand, the respective aspects of the language (error handling) is pretty much the same in python and javascript. What is the difference? Why one community finds a feature useful and the other - completely not?

P. S. I am not really asking if you consider context managers useful, just what is the possible difference between js/nodejs and python in this aspect.

@rfk
Copy link

rfk commented Nov 4, 2016

You might also find some inspiration from the resource-management APIs provided by bluebird:

http://bluebirdjs.com/docs/api/resource-management.html
http://bluebirdjs.com/docs/api/disposer.html

Although the documentation there is not terribly clear for newcomers, I think it's in the ballpark of what you're describing here.

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