from __future__ import annotations import contextlib import os from pathlib import Path from typing import TYPE_CHECKING, Literal, TypedDict, get_args from polars._dependencies import json from polars._typing import EngineType from polars._utils.deprecation import deprecated from polars._utils.unstable import unstable from polars._utils.various import normalize_filepath from polars.lazyframe.engine_config import GPUEngine if TYPE_CHECKING: import sys from types import TracebackType from polars._typing import FloatFmt from polars.io.cloud.credential_provider._providers import ( CredentialProviderFunction, ) if sys.version_info >= (3, 10): from typing import TypeAlias else: from typing_extensions import TypeAlias if sys.version_info >= (3, 11): from typing import Self, Unpack else: from typing_extensions import Self, Unpack if sys.version_info >= (3, 13): from warnings import deprecated else: from typing_extensions import deprecated # noqa: TC004 __all__ = ["Config"] TableFormatNames: TypeAlias = Literal[ "ASCII_FULL", "ASCII_FULL_CONDENSED", "ASCII_NO_BORDERS", "ASCII_BORDERS_ONLY", "ASCII_BORDERS_ONLY_CONDENSED", "ASCII_HORIZONTAL_ONLY", "ASCII_MARKDOWN", "MARKDOWN", "UTF8_FULL", "UTF8_FULL_CONDENSED", "UTF8_NO_BORDERS", "UTF8_BORDERS_ONLY", "UTF8_HORIZONTAL_ONLY", "NOTHING", ] # note: register all Config-specific environment variable names here; need to constrain # which 'POLARS_' environment variables are recognized, as there are other lower-level # and/or unstable settings that should not be saved or reset with the Config vars. _POLARS_CFG_ENV_VARS = { "POLARS_WARN_UNSTABLE", "POLARS_FMT_MAX_COLS", "POLARS_FMT_MAX_ROWS", "POLARS_FMT_NUM_DECIMAL", "POLARS_FMT_NUM_GROUP_SEPARATOR", "POLARS_FMT_NUM_LEN", "POLARS_FMT_STR_LEN", "POLARS_FMT_TABLE_CELL_ALIGNMENT", "POLARS_FMT_TABLE_CELL_LIST_LEN", "POLARS_FMT_TABLE_CELL_NUMERIC_ALIGNMENT", "POLARS_FMT_TABLE_DATAFRAME_SHAPE_BELOW", "POLARS_FMT_TABLE_FORMATTING", "POLARS_FMT_TABLE_HIDE_COLUMN_DATA_TYPES", "POLARS_FMT_TABLE_HIDE_COLUMN_NAMES", "POLARS_FMT_TABLE_HIDE_COLUMN_SEPARATOR", "POLARS_FMT_TABLE_HIDE_DATAFRAME_SHAPE_INFORMATION", "POLARS_FMT_TABLE_INLINE_COLUMN_DATA_TYPE", "POLARS_FMT_TABLE_ROUNDED_CORNERS", "POLARS_STREAMING_CHUNK_SIZE", "POLARS_TABLE_WIDTH", "POLARS_VERBOSE", "POLARS_MAX_EXPR_DEPTH", "POLARS_ENGINE_AFFINITY", } # vars that set the rust env directly should declare themselves here as the Config # method name paired with a callable that returns the current state of that value: with contextlib.suppress(ImportError, NameError): # note: 'plr' not available when building docs import polars._plr as plr _POLARS_CFG_DIRECT_VARS = { "set_fmt_float": plr.get_float_fmt, "set_float_precision": plr.get_float_precision, "set_thousands_separator": plr.get_thousands_separator, "set_decimal_separator": plr.get_decimal_separator, "set_trim_decimal_zeros": plr.get_trim_decimal_zeros, } class ConfigParameters(TypedDict, total=False): """Parameters supported by the polars Config.""" ascii_tables: bool | None auto_structify: bool | None decimal_separator: str | None thousands_separator: str | bool | None float_precision: int | None fmt_float: FloatFmt | None fmt_str_lengths: int | None fmt_table_cell_list_len: int | None streaming_chunk_size: int | None tbl_cell_alignment: Literal["LEFT", "CENTER", "RIGHT"] | None tbl_cell_numeric_alignment: Literal["LEFT", "CENTER", "RIGHT"] | None tbl_cols: int | None tbl_column_data_type_inline: bool | None tbl_dataframe_shape_below: bool | None tbl_formatting: TableFormatNames | None tbl_hide_column_data_types: bool | None tbl_hide_column_names: bool | None tbl_hide_dtype_separator: bool | None tbl_hide_dataframe_shape: bool | None tbl_rows: int | None tbl_width_chars: int | None trim_decimal_zeros: bool | None verbose: bool | None expr_depth_warning: int set_ascii_tables: bool | None set_auto_structify: bool | None set_decimal_separator: str | None set_thousands_separator: str | bool | None set_float_precision: int | None set_fmt_float: FloatFmt | None set_fmt_str_lengths: int | None set_fmt_table_cell_list_len: int | None set_streaming_chunk_size: int | None set_tbl_cell_alignment: Literal["LEFT", "CENTER", "RIGHT"] | None set_tbl_cell_numeric_alignment: Literal["LEFT", "CENTER", "RIGHT"] | None set_tbl_cols: int | None set_tbl_column_data_type_inline: bool | None set_tbl_dataframe_shape_below: bool | None set_tbl_formatting: TableFormatNames | None set_tbl_hide_column_data_types: bool | None set_tbl_hide_column_names: bool | None set_tbl_hide_dtype_separator: bool | None set_tbl_hide_dataframe_shape: bool | None set_tbl_rows: int | None set_tbl_width_chars: int | None set_trim_decimal_zeros: bool | None set_verbose: bool | None set_expr_depth_warning: int set_engine_affinity: EngineType | None class Config(contextlib.ContextDecorator): """ Configure polars; offers options for table formatting and more. Notes ----- Can also be used as a context manager OR a function decorator in order to temporarily scope the lifetime of specific options. For example: >>> with pl.Config() as cfg: ... # set verbose for more detailed output within the scope ... cfg.set_verbose(True) # doctest: +IGNORE_RESULT >>> # scope exit - no longer in verbose mode This can also be written more compactly as: >>> with pl.Config(verbose=True): ... pass (The compact format is available for all `Config` methods that take a single value). Alternatively, you can use as a decorator in order to scope the duration of the selected options to a specific function: >>> @pl.Config(verbose=True) ... def test(): ... pass """ _context_options: ConfigParameters | None = None _original_state: str = "" def __init__( self, *, restore_defaults: bool = False, apply_on_context_enter: bool = False, **options: Unpack[ConfigParameters], ) -> None: """ Initialise a Config object instance for context manager usage. Any `options` kwargs should correspond to the available named "set_*" methods, but are allowed to omit the "set_" prefix for brevity. Parameters ---------- restore_defaults set all options to their default values (this is applied before setting any other options). apply_on_context_enter defer applying the options until a context is entered. This allows you to create multiple `Config` instances with different options, and then reuse them independently as context managers or function decorators with specific bundles of parameters. **options keyword args that will set the option; equivalent to calling the named "set_