Python typing.ContextManager() Examples
The following are 30
code examples of typing.ContextManager().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
typing
, or try the search function
.
Example #1
Source File: packed.py From wasabi2d with GNU Lesser General Public License v3.0 | 6 votes |
def __init__( self, mode: int, ctx: moderngl.Context, prog: moderngl.Program, dtype: np.dtype, draw_context: ContextManager = nullcontext(), capacity: int = 256, index_capacity: int = 512): self.mode = mode self.ctx = ctx self.prog = prog self.dtype = dtype_to_moderngl(dtype) self.allocs: Dict[int, Tuple[slice, np.ndarray]] = {} self.verts = MemoryBackedBuffer(ctx, capacity, dtype) self.indexes = IndexBuffer(ctx) self.draw_context = draw_context self.dirty = False
Example #2
Source File: sqlalchemy.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
def _handle_error(context, *args): # type: (Any, *Any) -> None conn = context.connection span = getattr(conn, "_sentry_sql_span", None) # type: Optional[Span] if span is not None: span.set_status("internal_error") # _after_cursor_execute does not get called for crashing SQL stmts. Judging # from SQLAlchemy codebase it does seem like any error coming into this # handler is going to be fatal. ctx_mgr = getattr( conn, "_sentry_sql_span_manager", None ) # type: ContextManager[Any] if ctx_mgr is not None: conn._sentry_sql_span_manager = None ctx_mgr.__exit__(None, None, None)
Example #3
Source File: absltest.py From abseil-py with Apache License 2.0 | 6 votes |
def open_text(self, mode='rt', encoding='utf8', errors='strict'): # type: (Text, Text, Text) -> ContextManager[TextIO] """Return a context manager for opening the file in text mode. Args: mode: The mode to open the file in. The "t" flag is implicit if not already present. It must not have the "b" flag. encoding: The encoding to use when opening the file. errors: How to handle decoding errors. Returns: Context manager that yields an open file. Raises: ValueError: if invalid inputs are provided. """ if 'b' in mode: raise ValueError('Invalid mode {!r}: "b" flag not allowed when opening ' 'file in text mode'.format(mode)) if 't' not in mode: mode += 't' cm = self._open(mode, encoding, errors) # type: ContextManager[TextIO] return cm
Example #4
Source File: absltest.py From abseil-py with Apache License 2.0 | 6 votes |
def open_bytes(self, mode='rb'): # type: (Text) -> ContextManager[BinaryIO] """Return a context manager for opening the file in binary mode. Args: mode: The mode to open the file in. The "b" mode is implicit if not already present. It must not have the "t" flag. Returns: Context manager that yields an open file. Raises: ValueError: if invalid inputs are provided. """ if 't' in mode: raise ValueError('Invalid mode {!r}: "t" flag not allowed when opening ' 'file in binary mode'.format(mode)) if 'b' not in mode: mode += 'b' cm = self._open(mode, encoding=None, errors=None) # type: ContextManager[BinaryIO] return cm # TODO(b/123775699): Once pytype supports typing.Literal, use overload and # Literal to express more precise return types and remove the type comments in # open_text and open_bytes.
Example #5
Source File: hub.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
def push_scope( # noqa self, callback=None # type: Optional[Callable[[Scope], None]] ): # type: (...) -> Optional[ContextManager[Scope]] """ Pushes a new layer on the scope stack. :param callback: If provided, this method pushes a scope, calls `callback`, and pops the scope again. :returns: If no `callback` is provided, a context manager that should be used to pop the scope again. """ if callback is not None: with self.push_scope() as scope: callback(scope) return None client, scope = self._stack[-1] new_layer = (client, copy.copy(scope)) self._stack.append(new_layer) return _ScopeManager(self)
Example #6
Source File: absltest.py From abseil-py with Apache License 2.0 | 6 votes |
def enter_context(self, manager): """Returns the CM's value after registering it with the exit stack. Entering a context pushes it onto a stack of contexts. The context is exited when the test completes. Contexts are are exited in the reverse order of entering. They will always be exited, regardless of test failure/success. The context stack is specific to the test being run. This is useful to eliminate per-test boilerplate when context managers are used. For example, instead of decorating every test with `@mock.patch`, simply do `self.foo = self.enter_context(mock.patch(...))' in `setUp()`. NOTE: The context managers will always be exited without any error information. This is an unfortunate implementation detail due to some internals of how unittest runs tests. Args: manager: The context manager to enter. """ # type: (ContextManager[_T]) -> _T if not self._exit_stack: raise AssertionError( 'self._exit_stack is not set: enter_context is Py3-only; also make ' 'sure that AbslTest.setUp() is called.') return self._exit_stack.enter_context(manager)
Example #7
Source File: io.py From cjworkbench with GNU Affero General Public License v3.0 | 6 votes |
def downloaded_file(stored_object: StoredObject, dir=None) -> ContextManager[Path]: """ Context manager to download and yield `path`, the StoredObject's file. Raise FileNotFoundError if the object is missing. Usage: try: with storedobjects.downloaded_file(stored_object) as path: # do something with `path`, a `pathlib.Path` except FileNotFoundError: # file does not exist.... """ if stored_object.size == 0: # Some stored objects with size=0 do not have key. These are valid: # they represent empty files. return tempfile_context(prefix="storedobjects-empty-file", dir=dir) else: # raises FileNotFoundError return minio.temporarily_download( minio.StoredObjectsBucket, stored_object.key, dir=dir )
Example #8
Source File: util.py From cjworkbench with GNU Affero General Public License v3.0 | 6 votes |
def arrow_table_context( table: Union[Dict[str, List[Any]], pyarrow.Table], columns: Optional[List[Column]] = None, dir: Optional[pathlib.Path] = None, ) -> ContextManager[ArrowTable]: """ Yield an ArrowTable (whose `.path` is a file). Metadata is inferred. Number columns have format `{:,}`. """ if isinstance(table, dict): table = pyarrow.table(table) if columns is None: columns = [ _arrow_column_to_column(name, col) for name, col in zip(table.column_names, table.columns) ] metadata = TableMetadata(table.num_rows, columns) if metadata.columns: with arrow_file(table, dir=dir) as path: yield ArrowTable(path, table, metadata) else: yield ArrowTable(None, None, metadata)
Example #9
Source File: chroot.py From cjworkbench with GNU Affero General Public License v3.0 | 6 votes |
def writable_file(self, path: Path) -> ContextManager[None]: """ Flag a file as "writable" by a module. `path` must exist -- that is, the module must be "overwriting" a file (writing to overlayfs, which stores the written file in an output layer). The logic is: save the original attributes; then make the file world-writable. When the context exits, restore the original attributes. Raise ModuleExitedError if the module tried to inject a symlink. """ old_stat = path.stat() path.chmod(0o666) try: yield finally: self._reown_output_file(path, old_stat)
Example #10
Source File: _py3.py From pipenv with MIT License | 6 votes |
def path( package: Package, resource: Resource, ) -> 'ContextManager[Path]': """A context manager providing a file path object to the resource. If the resource does not already exist on its own on the file system, a temporary file will be created. If the file was created, the file will be deleted upon exiting the context manager (no exception is raised if the file was deleted prior to the context manager exiting). """ reader = _get_resource_reader(_get_package(package)) return ( _path_from_reader(reader, resource) if reader else _common.as_file(files(package).joinpath(_normalize_path(resource))) )
Example #11
Source File: minio.py From cjworkbench with GNU Affero General Public License v3.0 | 6 votes |
def temporarily_download( bucket: str, key: str, dir=None ) -> ContextManager[pathlib.Path]: """ Copy a file from S3 to a pathlib.Path; yield; and delete. Raise FileNotFoundError if the key is not on S3. Usage: with minio.temporarily_download('bucket', 'key') as path: print(str(path)) # a path on the filesystem path.read_bytes() # returns file contents # when you exit the block, the pathlib.Path is deleted """ with tempfile_context(prefix="minio-download-", dir=dir) as path: download(bucket, key, path) # raise FileNotFoundError (deleting path) yield path
Example #12
Source File: test_task_script.py From trains-agent with Apache License 2.0 | 6 votes |
def iterate_output(timeout, command): # type: (int, Argv) -> ContextManager[Iterator[Text]] """ Run `command` in a subprocess and return a contextmanager of an iterator over its output's lines. If `timeout` seconds have passed, iterator ends and the process is killed. :param timeout: maximum amount of time to wait for command to end :param command: command to run """ log.info("running: %s", command) process = command.call_subprocess( subprocess.Popen, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) try: yield _iterate_output(timeout, process) finally: status = process.poll() if status is not None: log.info("command %s terminated, status: %s", command, status) else: log.info("killing command %s", command) process.kill()
Example #13
Source File: chroot.py From cjworkbench with GNU Affero General Public License v3.0 | 5 votes |
def tempdir_context(self, prefix=None, suffix=None) -> ContextManager[Path]: """ Yield a directory where files are writable to us and read-only to modules. The directory will be world-readable. Module code that _writes_ to this directory will produce new output in self.chroot.upper. """ tmp = self.chroot.root / "var" / "tmp" with tempdir_context(prefix=prefix, suffix=suffix, dir=tmp) as path: path.chmod(0o755) yield path
Example #14
Source File: util.py From cjworkbench with GNU Affero General Public License v3.0 | 5 votes |
def tempdir_context(prefix=None, suffix=None, dir=None) -> ContextManager[Path]: path = create_tempdir(prefix=prefix, suffix=suffix, dir=dir) try: yield path finally: with contextlib.suppress(FileNotFoundError): shutil.rmtree(path)
Example #15
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def attach(self, input_ready_callback: Callable[[], None]) -> ContextManager[None]: return _dummy_context_manager()
Example #16
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def cooked_mode(self) -> ContextManager[None]: return _dummy_context_manager()
Example #17
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def raw_mode(self) -> ContextManager[None]: return _dummy_context_manager()
Example #18
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def attach(self, input_ready_callback: Callable[[], None]) -> ContextManager[None]: """ Return a context manager that makes this input active in the current event loop. """
Example #19
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def cooked_mode(self) -> ContextManager[None]: """ Context manager that turns the input into cooked mode. """
Example #20
Source File: chroot.py From cjworkbench with GNU Affero General Public License v3.0 | 5 votes |
def tempfile_context( self, prefix=None, suffix=None, dir=None ) -> ContextManager[Path]: """ Yield a temporary file in `dir`, readable by module code. `dir` must have been yielded from `self.tempdir_context()`. """ assert dir is not None and str(dir).startswith( str(self.chroot.root) ), "please pass a dir yielded from Chroot.tempdir_context()." with tempfile_context(prefix=prefix, suffix=suffix, dir=dir) as path: path.chmod(0o644) yield path
Example #21
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def raw_mode(self) -> ContextManager[None]: """ Context manager that turns the input into raw mode. """
Example #22
Source File: win32_pipe.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def cooked_mode(self) -> ContextManager[None]: return DummyContext()
Example #23
Source File: win32_pipe.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def raw_mode(self) -> ContextManager[None]: return DummyContext()
Example #24
Source File: win32_pipe.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def attach(self, input_ready_callback: Callable) -> ContextManager[None]: """ Return a context manager that makes this input active in the current event loop. """ return attach_win32_input(self, input_ready_callback)
Example #25
Source File: win32.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def cooked_mode(self) -> ContextManager[None]: return cooked_mode()
Example #26
Source File: win32.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def raw_mode(self) -> ContextManager[None]: return raw_mode()
Example #27
Source File: win32.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def detach(self) -> ContextManager[None]: """ Return a context manager that makes sure that this input is not active in the current event loop. """ return detach_win32_input(self)
Example #28
Source File: win32.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def attach(self, input_ready_callback: Callable[[], None]) -> ContextManager[None]: """ Return a context manager that makes this input active in the current event loop. """ return attach_win32_input(self, input_ready_callback)
Example #29
Source File: command_context.py From rules_pip with MIT License | 5 votes |
def enter_context(self, context_provider): # type: (ContextManager[_T]) -> _T assert self._in_main_context return self._main_context.enter_context(context_provider)
Example #30
Source File: posix_pipe.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def raw_mode(self) -> ContextManager[None]: return DummyContext()