Comment Comment by tibordp Python context managers are actually very similar to guard objects in C++ and Rust.What I meant was something like this (could also be done with `contextlib`, but it's also verbose) seen_names = {} class EnsureUnique: def __init__(self, name: str): self.name = name def __enter__(self): if self.name in seen_names: raise ValueError(f"Duplicate name: {self.name}") seen_names.add(self.name) def __exit__(self, exc_type, exc_value, traceback): seen_names.remove(self.name) def bar(): with EnsureUnique("foo"): do_something() ... With defer this could be simplified to static seen_names: HashSet<&[u8]> = HashSet::new(); fn bar() { if !seen_names.insert("foo") { panic!("Duplicate name: foo") } defer seen_names.remove("foo"); do_something(); } parent tibordp 4 years ago
What I meant was something like this (could also be done with `contextlib`, but it's also verbose)
With defer this could be simplified to