1

In Python, you can use context managers to allocate and release resources within a block of code, such as opening and closing a file handle within the scope of a with block in this example:

with open('some_file', 'w') as opened_file:
    opened_file.write('Can Chapel do this!?')

Does a similar feature exist in Chapel? If so, how would you translate the above code example to Chapel?

ben-albrecht
  • 1,785
  • 10
  • 23
  • Maybe I miss some key, unsaid, point here, yet - why would a "mimicking" a concurrency-preventing Python, where GIL-lock avoids any benefits from even a just-[CONCURRENT] processing co-existence, by "mirroring" a syntax sugar constructors (for scope-limitations), ever help to improve Chapel in the fields of un-paralleled True-[PARALLEL] NUMA-infrastructure hardware mapped HPC processing and a **programming**-productivity ( hard to see in any other HPC-domain stack of programming languages and OpenMP+MPI+slurm tools from even seasoned HPC-professionals )? Could you add some such reason for it? – user3666197 Jan 06 '22 at 06:52
  • 1
    Even in the largest parallel programs, there are large chunks of serial code where traditional non-HPC language constructs can be a productivity boon to programmers. For example, rather than having to explicitly have pairs of start/stop calls to timers, communication diagnostic routines, etc., context managers can serve as an attractive way to govern such enter/exit pairs cleanly. We have also been looking at them as a tool to perform otherwise type-unsafe operations such as reallocating arrays whose elements' types have no default value. – Brad Jan 08 '22 at 17:19

1 Answers1

1

Chapel introduced context manager support in Chapel 1.25 via the manage statement.

Here is a similar example from above. Note that builtin types do not yet include the enterThis() and leaveThis() methods necessary for context management to work. Therefore, we need to define those methods before using the manage statement in Chapel 1.25. This should not be necessary in future versions.

use IO;

// This should be part of standard library eventually
proc file.enterThis() ref { return this; }
proc file.leaveThis(in err: owned Error?) { this.close(); }


manage open('some_file.txt', iomode.cw) as f {
  var w = f.writer();
  w.write('yes');
}
ben-albrecht
  • 1,785
  • 10
  • 23