[PYTHON] Various ways to destroy resources with scope

RAII(C++)

See from wikipedia. The destructor is called by destroying the automatic variable, and the resource is closed at that time. It is assumed that the close API does not raise an exception. Like perl's guard module.

void functionA()
{
    LogFile log("Output log of functionA");
 
    log.write("fun Step succeeded");
 
    // ...Continue to use log...
    //Whether an exception is thrown or a function returns, the log file handle is reliably closed.
}

with clause (python)

It didn't exist in the past, but it has increased.

with open("hello.txt") as f:
    for line in f:
        print line

proc receipt (ruby)

Receives closure and allocates and destroys resources before and after execution of the function.

open("foo.csv") {|file|
  while l = file.gets
    lines += 1
    fields += l.split(',').size
  end
}

using clause (C #)

I want to see c # with.

//If you implement the Dispose method, you can use it after exiting using

using (StreamWriter writer = 
                new StreamWriter("memo.txt", false, Encoding.UTF8))
{
    writer.Write("text");
}

scope(D-lang)

The function after scope is evaluated on escape.

void abc()
{
    Mutex m = new Mutex;

    lock(m);	//Lock mutex
    scope(exit) unlock(m);	//Unlock at end of scope

    foo();	//Do the processing
}

defer(go-lang)

Similar to scope

    f, err := os.Open(filename)
    if err != nil {
        return "", err
    }
    defer f.Close()  // f.Close is executed on completion

try-with-resources syntax (java)

It closes the one that implements AutoCloseable Interface. (Thanks to tsuyoshi_cho)

    public static void main(String[] args) {
        try (AutoCloseable imp = new AutoCloseableImpl()) { // New!
            System.out.println("hoge");
        } catch(Exception e) {
            System.out.println("catch:" + e);
        } finally {
            System.out.println("finally");
        }
    }

synchronized(Java) You can manage the acquisition of locks on objects with syntax.

class MyObject {
  int val;

  MyObject(int val) {
    this.val = val;
  }

  synchronized void setVal(int val) {
    this.val = val;
  }

  synchronized int getVal() {
    return val;
  }
}

For the time being, I will add it if I remember something.

Recommended Posts

Various ways to destroy resources with scope
2 ways to deal with SessionNotCreatedException
Various ways to create a dictionary (memories)
4 ways to deal with missing dict keys
[Python] List Comprehension Various ways to create a list
Various ways to extract columns in a NumPy array
Try to solve Sudoku in various ways (SAT, CSP)
Convert 202003 to 2020-03 with pandas
[Python] Various ways to generate data with Numpy (arange / linspace / logspace / zeros / ones /mgrid / ogrid)
Various colorbars with Matplotlib
I tried to make various "dummy data" with Python faker
I tried various methods to send Japanese mail with Python
Try to display various information useful for debugging with python