ID EN
Contextlib

nullcontext

Python 3.11 🇮🇩 Bahasa Indonesia

Mengembalikan pengelola konteks yang mengembalikan enter_result dari __enter__(), namun sebaliknya tidak melakukan apa pun. Ini dimaksudkan untuk digunakan sebagai pengganti pengelola konteks opsional, misalnya:

Syntax

PYTHON
contextlib.nullcontext(enter_result=None)

Contoh

Example 1
PYTHON
def myfunction(arg, ignore_exceptions=False):
    if ignore_exceptions:
         Use suppress to ignore all exceptions.
        cm = contextlib.suppress(Exception)
    else:
         Do not ignore any exceptions, cm has no effect.
        cm = contextlib.nullcontext()
    with cm:
         Do something
Example 2
PYTHON
def process_file(file_or_path):
    if isinstance(file_or_path, str):
         If string, open file
        cm = open(file_or_path)
    else:
         Caller is responsible for closing file
        cm = nullcontext(file_or_path)

    with cm as file:
         Perform processing on the file
Example 3
PYTHON
async def send_http(session=None):
    if not session:
         If no http session, create it with aiohttp
        cm = aiohttp.ClientSession()
    else:
         Caller is responsible for closing the session
        cm = nullcontext(session)

    async with cm as session:
         Send http requests with session

See Also

asynchronous context managers asynchronous context manager