datafusion.context#
SessionContext — entry point for running DataFusion queries.
A SessionContext holds registered tables, catalogs, and
configuration for the current session. It is the first object most programs
create: from it you register data, run SQL strings
(SessionContext.sql()), read files
(SessionContext.read_csv(),
SessionContext.read_parquet(), …), and construct
DataFrame objects in memory
(SessionContext.from_pydict(),
SessionContext.from_arrow()).
Session behavior (memory limits, batch size, configured optimizer passes,
…) is controlled by SessionConfig and
RuntimeEnvBuilder; SQL dialect limits are controlled by
SQLOptions.
Examples
>>> ctx = dfn.SessionContext()
>>> df = ctx.from_pydict({"a": [1, 2, 3]})
>>> ctx.sql("SELECT 1 AS n").to_pydict()
{'n': [1]}
See Concepts in the online documentation for the broader execution model.
Classes#
Type hint for object exporting Arrow C Array via Arrow PyCapsule Interface. |
|
Type hint for object exporting Arrow C Stream via Arrow PyCapsule Interface. |
|
Runtime configuration options. |
|
Options to be used when performing SQL queries. |
|
Session configuration options. |
|
This is the main interface for executing queries and creating DataFrames. |
|
Type hint for object that has __datafusion_table_provider__ PyCapsule. |
Module Contents#
- class datafusion.context.ArrowArrayExportable#
Bases:
ProtocolType hint for object exporting Arrow C Array via Arrow PyCapsule Interface.
https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html
- __arrow_c_array__(requested_schema: object | None = None) tuple[object, object]#
- class datafusion.context.ArrowStreamExportable#
Bases:
ProtocolType hint for object exporting Arrow C Stream via Arrow PyCapsule Interface.
https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html
- __arrow_c_stream__(requested_schema: object | None = None) object#
- class datafusion.context.RuntimeEnvBuilder#
Runtime configuration options.
Create a new
RuntimeEnvBuilderwith default values.- with_disk_manager_disabled() RuntimeEnvBuilder#
Disable the disk manager, attempts to create temporary files will error.
- Returns:
A new
RuntimeEnvBuilderobject with the updated setting.
- with_disk_manager_os() RuntimeEnvBuilder#
Use the operating system’s temporary directory for disk manager.
- Returns:
A new
RuntimeEnvBuilderobject with the updated setting.
- with_disk_manager_specified(*paths: str | pathlib.Path) RuntimeEnvBuilder#
Use the specified paths for the disk manager’s temporary files.
- Parameters:
paths – Paths to use for the disk manager’s temporary files.
- Returns:
A new
RuntimeEnvBuilderobject with the updated setting.
- with_fair_spill_pool(size: int) RuntimeEnvBuilder#
Use a fair spill pool with the specified size.
This pool works best when you know beforehand the query has multiple spillable operators that will likely all need to spill. Sometimes it will cause spills even when there was sufficient memory (reserved for other operators) to avoid doing so:
┌───────────────────────z──────────────────────z───────────────┐ │ z z │ │ z z │ │ Spillable z Unspillable z Free │ │ Memory z Memory z Memory │ │ z z │ │ z z │ └───────────────────────z──────────────────────z───────────────┘
- Parameters:
size – Size of the memory pool in bytes.
- Returns:
A new
RuntimeEnvBuilderobject with the updated setting.
Examples
>>> config = dfn.RuntimeEnvBuilder().with_fair_spill_pool(1024)
- with_greedy_memory_pool(size: int) RuntimeEnvBuilder#
Use a greedy memory pool with the specified size.
This pool works well for queries that do not need to spill or have a single spillable operator. See
with_fair_spill_pool()if there are multiple spillable operators that all will spill.- Parameters:
size – Size of the memory pool in bytes.
- Returns:
A new
RuntimeEnvBuilderobject with the updated setting.
Examples
>>> config = dfn.RuntimeEnvBuilder().with_greedy_memory_pool(1024)
- with_temp_file_path(path: str | pathlib.Path) RuntimeEnvBuilder#
Use the specified path to create any needed temporary files.
- Parameters:
path – Path to use for temporary files.
- Returns:
A new
RuntimeEnvBuilderobject with the updated setting.
Examples
>>> config = dfn.RuntimeEnvBuilder().with_temp_file_path("/tmp")
- with_unbounded_memory_pool() RuntimeEnvBuilder#
Use an unbounded memory pool.
- Returns:
A new
RuntimeEnvBuilderobject with the updated setting.
- config_internal#
- class datafusion.context.SQLOptions#
Options to be used when performing SQL queries.
Create a new
SQLOptionswith default values.The default values are: - DDL commands are allowed - DML commands are allowed - Statements are allowed
- with_allow_ddl(allow: bool = True) SQLOptions#
Should DDL (Data Definition Language) commands be run?
Examples of DDL commands include
CREATE TABLEandDROP TABLE.- Parameters:
allow – Allow DDL commands to be run.
- Returns:
A new
SQLOptionsobject with the updated setting.
Examples
>>> options = dfn.SQLOptions().with_allow_ddl(True)
- with_allow_dml(allow: bool = True) SQLOptions#
Should DML (Data Manipulation Language) commands be run?
Examples of DML commands include
INSERT INTOandDELETE.- Parameters:
allow – Allow DML commands to be run.
- Returns:
A new
SQLOptionsobject with the updated setting.
Examples
>>> options = dfn.SQLOptions().with_allow_dml(True)
- with_allow_statements(allow: bool = True) SQLOptions#
Should statements such as
SET VARIABLEandBEGIN TRANSACTIONbe run?- Parameters:
allow – Allow statements to be run.
- Returns:
py:class:SQLOptions` object with the updated setting.
- Return type:
A new
Examples
>>> options = dfn.SQLOptions().with_allow_statements(True)
- options_internal#
- class datafusion.context.SessionConfig(config_options: dict[str, str] | None = None)#
Session configuration options.
Create a new
SessionConfigwith the given configuration options.Each entry is applied as though passed to
set(), so the same keys are rejected. See Configuration.- Parameters:
config_options – Options to apply, keyed by fully qualified name.
- Raises:
ValueError – If a key names no known option, or a value does not parse as that option’s declared type. Which of several bad entries is reported is not defined.
Example usage:
>>> from datafusion import SessionConfig, SessionContext >>> ctx = SessionContext(SessionConfig()) >>> config = SessionConfig( ... config_options={"datafusion.execution.batch_size": "1024"} ... ) >>> ctx = SessionContext(config.with_information_schema(True)) >>> ctx.sql( ... "select value from information_schema.df_settings" ... " where name = 'datafusion.execution.batch_size'" ... ).collect()[0]["value"][0] <pyarrow.StringScalar: '1024'>
- set(key: str, value: str) SessionConfig#
Set a configuration option by its fully qualified key.
Not every key that
information_schema.df_settingslists can be set here: thedatafusion.runtime.*entries come from the runtime environment rather than from the session config. See Configuration.- Parameters:
key – Option key including its namespace, such as
datafusion.execution.batch_size.value – Option value as a string, parsed according to the type the option declares.
- Returns:
This
SessionConfig, modified in place, so that calls chain.- Raises:
ValueError – If
keynames no known option, or ifvaluedoes not parse as that option’s declared type.
Example usage:
>>> from datafusion import SessionConfig, SessionContext >>> config = SessionConfig().set("datafusion.execution.batch_size", "1024") >>> ctx = SessionContext(config.with_information_schema(True)) >>> ctx.sql( ... "select value from information_schema.df_settings" ... " where name = 'datafusion.execution.batch_size'" ... ).collect()[0]["value"][0] <pyarrow.StringScalar: '1024'>
- with_batch_size(batch_size: int) SessionConfig#
Customize batch size.
- Parameters:
batch_size – Batch size.
- Returns:
A new
SessionConfigobject with the updated setting.
- with_create_default_catalog_and_schema(enabled: bool = True) SessionConfig#
Control if the default catalog and schema will be automatically created.
- Parameters:
enabled – Whether the default catalog and schema will be automatically created.
- Returns:
A new
SessionConfigobject with the updated setting.
- with_default_catalog_and_schema(catalog: str, schema: str) SessionConfig#
Select a name for the default catalog and schema.
- Parameters:
catalog – Catalog name.
schema – Schema name.
- Returns:
A new
SessionConfigobject with the updated setting.
- with_extension(extension: Any) SessionConfig#
Create a new configuration using an extension.
- Parameters:
extension – A custom configuration extension object. These are
library. (shared from another DataFusion extension)
- Returns:
A new
SessionConfigobject with the updated setting.
- with_information_schema(enabled: bool = True) SessionConfig#
Enable or disable the inclusion of
information_schemavirtual tables.- Parameters:
enabled – Whether to include
information_schemavirtual tables.- Returns:
A new
SessionConfigobject with the updated setting.
- with_parquet_pruning(enabled: bool = True) SessionConfig#
Enable or disable the use of pruning predicate for parquet readers.
Pruning predicates will enable the reader to skip row groups.
- Parameters:
enabled – Whether to use pruning predicate for parquet readers.
- Returns:
A new
SessionConfigobject with the updated setting.
- with_repartition_aggregations(enabled: bool = True) SessionConfig#
Enable or disable the use of repartitioning for aggregations.
Enabling this improves parallelism.
- Parameters:
enabled – Whether to use repartitioning for aggregations.
- Returns:
A new
SessionConfigobject with the updated setting.
- with_repartition_file_min_size(size: int) SessionConfig#
Set minimum file range size for repartitioning scans.
- Parameters:
size – Minimum file range size.
- Returns:
A new
SessionConfigobject with the updated setting.
- with_repartition_file_scans(enabled: bool = True) SessionConfig#
Enable or disable the use of repartitioning for file scans.
- Parameters:
enabled – Whether to use repartitioning for file scans.
- Returns:
A new
SessionConfigobject with the updated setting.
- with_repartition_joins(enabled: bool = True) SessionConfig#
Enable or disable the use of repartitioning for joins to improve parallelism.
- Parameters:
enabled – Whether to use repartitioning for joins.
- Returns:
A new
SessionConfigobject with the updated setting.
- with_repartition_sorts(enabled: bool = True) SessionConfig#
Enable or disable the use of repartitioning for window functions.
This may improve parallelism.
- Parameters:
enabled – Whether to use repartitioning for window functions.
- Returns:
A new
SessionConfigobject with the updated setting.
- with_repartition_windows(enabled: bool = True) SessionConfig#
Enable or disable the use of repartitioning for window functions.
This may improve parallelism.
- Parameters:
enabled – Whether to use repartitioning for window functions.
- Returns:
A new
SessionConfigobject with the updated setting.
- with_target_partitions(target_partitions: int) SessionConfig#
Customize the number of target partitions for query execution.
Increasing partitions can increase concurrency.
- Parameters:
target_partitions – Number of target partitions.
- Returns:
A new
SessionConfigobject with the updated setting.
- config_internal#
- class datafusion.context.SessionContext(config: SessionConfig | None = None, runtime: RuntimeEnvBuilder | None = None)#
This is the main interface for executing queries and creating DataFrames.
See Concepts in the online documentation for more information.
A context is a handle on a session, not the session itself. The
with_*methods —with_logical_extension_codec(),with_physical_extension_codec(),with_python_udf_inlining(), andwith_extensions()— return a new context wrapping the same underlying session. Only the Python-side codec settings differ; catalogs, tables, registered functions, and configuration are the one shared session, so a registration through either handle is visible to both.A few things therefore belong to the session rather than to a handle, and take effect even if the handle that set them is discarded: the query planner (see
set_query_planner()), and the rebuild of an installed foreign planner that follows installing a codec. Sessions, handles, and lifetimes in the online documentation works through when that matters.Keep a context alive for as long as anything derived from it is in use. A
DataFrame, logical plan, or exported capsule does not extend the session’s lifetime. Once the last context on a session is collected, any operation that reaches an extension codec fails withTaskContextProvider went out of scope over FFI boundary.Main interface for executing queries with DataFusion.
Maintains the state of the connection between a user and an instance of the connection between a user and an instance of the DataFusion engine.
- Parameters:
config – Session configuration options.
runtime – Runtime configuration options.
Example usage:
The following example demonstrates how to use the context to execute a query against a CSV data source using the
DataFrameAPI:from datafusion import SessionContext ctx = SessionContext() df = ctx.read_csv("data.csv")
- __datafusion_logical_extension_codec__(session: Any = None) Any#
Access the PyCapsule FFI_LogicalExtensionCodec.
sessionis accepted so a context satisfies the same protocol an extension library implements, where the argument is how the library reaches the host’s codec. A context already carries one, so the argument is ignored. SeeLogicalExtensionCodecExportablefor what an extension library does with it.- Parameters:
session – Accepted and ignored.
- Returns:
A
datafusion_logical_extension_codecPyCapsule.
Examples
>>> from datafusion import SessionContext >>> type(SessionContext().__datafusion_logical_extension_codec__()).__name__ 'PyCapsule'
- __datafusion_physical_extension_codec__(session: Any = None) Any#
Access the PyCapsule FFI_PhysicalExtensionCodec.
See
__datafusion_logical_extension_codec__()forsession.- Parameters:
session – Accepted and ignored.
- Returns:
A
datafusion_physical_extension_codecPyCapsule.
Examples
>>> from datafusion import SessionContext >>> ctx = SessionContext() >>> type(ctx.__datafusion_physical_extension_codec__()).__name__ 'PyCapsule'
- __datafusion_query_planner__(session: Any = None) Any#
Access the
FFI_QueryPlannerPyCapsule for the current planner.This is how you capture the planner a session already has in order to wrap it. Capture it before installing the new one, since
set_query_planner()replaces rather than layers.- Parameters:
session – Accepted and ignored. See
__datafusion_logical_extension_codec__().- Returns:
A
datafusion_query_plannerPyCapsule wrapping the session’s current planner, exported for a foreign planner to delegate to.
Examples
>>> from datafusion import SessionContext >>> ctx = SessionContext() >>> fallback = ctx.__datafusion_query_planner__() >>> type(fallback).__name__ 'PyCapsule'
Both spellings work, since the argument is ignored:
>>> type(ctx.__datafusion_query_planner__(ctx)).__name__ 'PyCapsule'
- __datafusion_task_context_provider__() Any#
Access the PyCapsule FFI_TaskContextProvider.
- __repr__() str#
Print a string representation of the Session Context.
- static _convert_file_sort_order(file_sort_order: collections.abc.Sequence[collections.abc.Sequence[datafusion.expr.SortKey]] | None) list[list[datafusion._internal.expr.SortExpr]] | None#
Convert nested
SortKeysequences into raw sort expressions.Each
SortKeycan be a column name string, anExpr, or aSortExprand will be converted usingdatafusion.expr.sort_list_to_raw_sort_list().
- static _convert_table_partition_cols(table_partition_cols: list[tuple[str, str | pyarrow.DataType]]) list[tuple[str, pyarrow.DataType]]#
- _register_object_store_for_path(path: str | pathlib.Path, store: Any) None#
Parse a URL path and register the given object store for its scheme and host.
This is a convenience helper used by methods like
register_parquet()andread_parquet()to automatically register an object store when anobject_storeparameter is provided.- Parameters:
path – A URL-style path (e.g.
"s3://bucket/key.parquet"or"file:///tmp/data.parquet").store – An object store instance to register.
- Raises:
ValueError – If the path does not contain a URL scheme, or if a non-file scheme is missing a host/bucket component.
- add_physical_optimizer_rule(rule: datafusion.extensions.PhysicalOptimizerRuleExportable) None#
Append a user-defined physical optimizer rule to the session.
The rule is imported via its
__datafusion_physical_optimizer_rule__PyCapsule, typically produced by a separate compiled extension. The underlyingSessionStateis rebuilt from its current state with the new rule appended, so previously registered tables, UDFs, and catalogs are preserved.- Parameters:
rule – Object exposing
__datafusion_physical_optimizer_rule__, aPhysicalOptimizerRuleExportable.
Examples
>>> from datafusion import SessionContext >>> ctx = SessionContext() >>> from my_extension import MyPhysicalOptimizerRule >>> rule = MyPhysicalOptimizerRule() >>> ctx.add_physical_optimizer_rule(rule)
- catalog(name: str = 'datafusion') datafusion.catalog.Catalog#
Retrieve a catalog by name.
- catalog_names() set[str]#
Returns the list of catalogs in this context.
- copied_config() SessionConfig#
Return a copy of the active
SessionConfig.Mutating the returned config does not affect this context; use the result when you need a starting point for a new context or want to inspect the current settings independent of further changes here.
Examples
>>> ctx = SessionContext(SessionConfig().with_batch_size(1024)) >>> isinstance(ctx.copied_config(), SessionConfig) True
- create_dataframe(partitions: list[list[pyarrow.RecordBatch]], name: str | None = None, schema: pyarrow.Schema | None = None) datafusion.dataframe.DataFrame#
Create and return a dataframe using the provided partitions.
- Parameters:
partitions –
pa.RecordBatchpartitions to register.name – Resultant dataframe name.
schema – Schema for the partitions.
- Returns:
DataFrame representation of the SQL query.
- create_dataframe_from_logical_plan(plan: datafusion.plan.LogicalPlan) datafusion.dataframe.DataFrame#
Create a
DataFramefrom an existing plan.- Parameters:
plan – Logical plan.
- Returns:
DataFrame representation of the logical plan.
- deregister_object_store(schema: str, host: str | None = None) None#
Remove an object store from the session.
- Parameters:
schema – The data source schema (e.g.
"s3://").host – URL for the host (e.g. bucket name).
- deregister_table(name: str) None#
Remove a table from the session.
- deregister_udaf(name: str) None#
Remove a user-defined aggregate function from the session.
- Parameters:
name – Name of the UDAF to deregister.
- deregister_udf(name: str) None#
Remove a user-defined scalar function from the session.
- Parameters:
name – Name of the UDF to deregister.
- deregister_udtf(name: str) None#
Remove a user-defined table function from the session.
- Parameters:
name – Name of the UDTF to deregister.
- deregister_udwf(name: str) None#
Remove a user-defined window function from the session.
- Parameters:
name – Name of the UDWF to deregister.
- empty_table() datafusion.dataframe.DataFrame#
Create an empty
DataFrame.
- enable_ident_normalization() bool#
Return whether identifier normalization (lowercasing) is enabled.
Examples
>>> ctx = SessionContext() >>> ctx.enable_ident_normalization() True
- enable_spark_functions() None#
Register all Spark-compatible functions for SQL access.
Registers every UDF/UDAF/UDWF from the
datafusion-sparkcrate, overriding any DataFusion built-ins of the same name with their Spark-semantics version (e.g.substringbecomes 1-indexed,concatpropagates NULL,rounduses HALF_UP rounding).For DataFrame use, import the typed wrappers from
datafusion.functions.sparkdirectly; this method is only needed for SQL queries.Examples
>>> ctx = dfn.SessionContext() >>> ctx.enable_spark_functions() >>> ctx.sql( ... "SELECT sha2('hello', 256) AS h" ... ).collect_column("h")[0].as_py() '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
- enable_url_table() SessionContext#
Control if local files can be queried as tables.
- Returns:
A new
SessionContextobject with url table enabled.
- execute(plan: datafusion.plan.ExecutionPlan, partition: int) datafusion.record_batch.RecordBatchStream#
Execute a single partition of
planand stream its batches.- Parameters:
plan – The physical plan to execute.
partition – Index of the partition to execute, in
range(plan.partition_count).
- Returns:
A stream over the record batches that partition produces.
- Raises:
ValueError – If
partitionis not a valid index forplan.OverflowError – If
partitionis negative, or too large to fit a platform-sized unsigned integer.
Example usage:
>>> import pyarrow as pa >>> from datafusion import SessionContext >>> ctx = SessionContext() >>> ctx.register_record_batches( ... "t", [[pa.record_batch({"a": [1, 2]})], [pa.record_batch({"a": [3]})]] ... ) >>> plan = ctx.sql("select a from t").execution_plan() >>> plan.partition_count 2 >>> sum( ... batch.to_pyarrow().num_rows ... for p in range(plan.partition_count) ... for batch in ctx.execute(plan, p) ... ) 3
- execute_logical_plan(plan: datafusion.plan.LogicalPlan) datafusion.dataframe.DataFrame#
Execute a
LogicalPlanand return a DataFrame.- Parameters:
plan – Logical plan to execute.
- Returns:
DataFrame resulting from the execution.
Examples
>>> ctx = SessionContext() >>> df = ctx.from_pydict({"a": [1, 2, 3]}) >>> plan = df.logical_plan() >>> df2 = ctx.execute_logical_plan(plan) >>> df2.collect()[0].column(0) <pyarrow.lib.Int64Array object at ...> [ 1, 2, 3 ]
- from_arrow(data: ArrowStreamExportable | ArrowArrayExportable, name: str | None = None) datafusion.dataframe.DataFrame#
Create a
DataFramefrom an Arrow source.The Arrow data source can be any object that implements either
__arrow_c_stream__or__arrow_c_array__. For the latter, it must return a struct array.Arrow data can be Polars, Pandas, Pyarrow etc.
- Parameters:
data – Arrow data source.
name – Name of the DataFrame.
- Returns:
DataFrame representation of the Arrow table.
- from_pandas(data: pandas.DataFrame, name: str | None = None) datafusion.dataframe.DataFrame#
Create a
DataFramefrom a Pandas DataFrame.- Parameters:
data – Pandas DataFrame.
name – Name of the DataFrame.
- Returns:
DataFrame representation of the Pandas DataFrame.
- from_polars(data: polars.DataFrame, name: str | None = None) datafusion.dataframe.DataFrame#
Create a
DataFramefrom a Polars DataFrame.- Parameters:
data – Polars DataFrame.
name – Name of the DataFrame.
- Returns:
DataFrame representation of the Polars DataFrame.
- from_pydict(data: dict[str, list[Any]], name: str | None = None) datafusion.dataframe.DataFrame#
Create a
DataFramefrom a dictionary.- Parameters:
data – Dictionary of lists.
name – Name of the DataFrame.
- Returns:
DataFrame representation of the dictionary of lists.
- from_pylist(data: list[dict[str, Any]], name: str | None = None) datafusion.dataframe.DataFrame#
Create a
DataFramefrom a list.- Parameters:
data – List of dictionaries.
name – Name of the DataFrame.
- Returns:
DataFrame representation of the list of dictionaries.
- classmethod global_ctx() SessionContext#
Retrieve the global context as a SessionContext wrapper.
- Returns:
A SessionContext object that wraps the global SessionContextInternal.
- logical_extension_codec_ids() list[str]#
List the logical extension codecs installed on this session.
Returns the identity of each installed codec, in install order. Those identities are what encoding stamps onto a payload and what decoding dispatches on, so this is how to check which library owns a plan and whether a session is able to decode one.
DataFusion’s own default codec is not listed. It handles whatever no installed codec claims, and it carries no identity to list.
- Returns:
The installed codec ids, in install order. Empty if none are installed.
Examples
>>> from datafusion import SessionContext >>> host = SessionContext() >>> host.logical_extension_codec_ids() [] >>> capsule = host.__datafusion_logical_extension_codec__() >>> ctx = SessionContext().with_logical_extension_codec( ... capsule, codec_id="my_library.Codec" ... ) >>> ctx.logical_extension_codec_ids() ['my_library.Codec']
- static parse_capacity_limit(config_name: str, limit: str) int#
Parse a size string into a byte count.
Accepts strings like
"100M","1.5G", or"512K"."0"is accepted and returns 0.config_nameis used purely for error messages and identifies which configuration setting the limit belongs to. Use this helper when constructing aRuntimeEnvBuilderfrom a human-friendly size string.Examples
>>> SessionContext.parse_capacity_limit( ... "datafusion.runtime.memory_limit", "1M" ... ) 1048576 >>> SessionContext.parse_capacity_limit( ... "datafusion.runtime.memory_limit", "0" ... ) 0
- parse_sql_expr(sql: str, schema: datafusion.common.DFSchema) datafusion.expr.Expr#
Parse a SQL expression string into a logical expression.
- Parameters:
sql – SQL expression string.
schema – Schema to use for resolving column references.
- Returns:
Parsed expression.
Examples
>>> from datafusion.common import DFSchema >>> ctx = SessionContext() >>> schema = DFSchema.empty() >>> ctx.parse_sql_expr("1 + 2", schema=schema) Expr(Int64(1) + Int64(2))
- physical_extension_codec_ids() list[str]#
List the physical extension codecs installed on this session.
See
logical_extension_codec_ids().- Returns:
The installed codec ids, in install order. Empty if none are installed.
Examples
>>> from datafusion import SessionContext >>> host = SessionContext() >>> host.physical_extension_codec_ids() [] >>> capsule = host.__datafusion_physical_extension_codec__() >>> ctx = SessionContext().with_physical_extension_codec( ... capsule, codec_id="my_library.PhysicalCodec" ... ) >>> ctx.physical_extension_codec_ids() ['my_library.PhysicalCodec']
- read_arrow(path: str | pathlib.Path, schema: pyarrow.Schema | None = None, file_extension: str = '.arrow', file_partition_cols: list[tuple[str, str | pyarrow.DataType]] | None = None, object_store: Any | None = None) datafusion.dataframe.DataFrame#
Create a
DataFramefor reading an Arrow IPC data source.- Parameters:
path – Path to the Arrow IPC file.
schema – The data source schema.
file_extension – File extension to select.
file_partition_cols – Partition columns.
object_store – A pre-configured object store instance to use for accessing the file. When provided, the store is automatically registered for the URL scheme and host parsed from
path.
- Returns:
DataFrame representation of the read Arrow IPC file.
Examples
>>> import tempfile, os >>> ctx = dfn.SessionContext() >>> table = pa.table({"a": [1, 2, 3]}) >>> with tempfile.TemporaryDirectory() as tmpdir: ... path = os.path.join(tmpdir, "data.arrow") ... with pa.ipc.new_file(path, table.schema) as writer: ... writer.write_table(table) ... df = ctx.read_arrow(path) ... df.collect()[0].column(0) <pyarrow.lib.Int64Array object at ...> [ 1, 2, 3 ]
Provide an explicit
schemato override schema inference:>>> with tempfile.TemporaryDirectory() as tmpdir: ... path = os.path.join(tmpdir, "data.arrow") ... with pa.ipc.new_file(path, table.schema) as writer: ... writer.write_table(table) ... df = ctx.read_arrow(path, schema=pa.schema([("a", pa.int64())])) ... df.collect()[0].column(0) <pyarrow.lib.Int64Array object at ...> [ 1, 2, 3 ]
Use
file_extensionto read files with a non-default extension:>>> with tempfile.TemporaryDirectory() as tmpdir: ... path = os.path.join(tmpdir, "data.ipc") ... with pa.ipc.new_file(path, table.schema) as writer: ... writer.write_table(table) ... df = ctx.read_arrow(path, file_extension=".ipc") ... df.collect()[0].column(0) <pyarrow.lib.Int64Array object at ...> [ 1, 2, 3 ]
- read_avro(path: str | pathlib.Path, schema: pyarrow.Schema | None = None, file_partition_cols: list[tuple[str, str | pyarrow.DataType]] | None = None, file_extension: str = '.avro', object_store: Any | None = None) datafusion.dataframe.DataFrame#
Create a
DataFramefor reading Avro data source.- Parameters:
path – Path to the Avro file.
schema – The data source schema.
file_partition_cols – Partition columns.
file_extension – File extension to select.
object_store – A pre-configured object store instance to use for accessing the file. When provided, the store is automatically registered for the URL scheme and host parsed from
path.
- Returns:
DataFrame representation of the read Avro file
- read_batch(batch: pyarrow.RecordBatch) datafusion.dataframe.DataFrame#
Return a
DataFramereading a single batch.Convenience wrapper around
read_batches()for the single-batch case. Unlikeregister_batch(), this does not register the batch as a named table; it returns an anonymousDataFramedirectly.- Parameters:
batch – Record batch to wrap as a DataFrame.
Examples
>>> ctx = dfn.SessionContext() >>> batch = pa.RecordBatch.from_pydict({"a": [1, 2, 3]}) >>> ctx.read_batch(batch).to_pydict() {'a': [1, 2, 3]}
- read_batches(batches: collections.abc.Iterable[pyarrow.RecordBatch]) datafusion.dataframe.DataFrame#
Return a
DataFramereading the given batches.All batches must share the same schema. Any iterable of
pa.RecordBatchis accepted (list, tuple, generator); it is materialized into a list before being handed to the underlying Rust binding. Unlikeregister_record_batches(), this does not register the batches as a named table; it returns an anonymousDataFramedirectly.- Parameters:
batches – Record batches to wrap as a DataFrame.
Examples
>>> ctx = dfn.SessionContext() >>> b1 = pa.RecordBatch.from_pydict({"a": [1, 2]}) >>> b2 = pa.RecordBatch.from_pydict({"a": [3, 4]}) >>> ctx.read_batches([b1, b2]).to_pydict() {'a': [1, 2, 3, 4]}
A generator works too:
>>> ctx.read_batches(b for b in [b1, b2]).to_pydict() {'a': [1, 2, 3, 4]}
- read_csv(path: str | pathlib.Path | list[str] | list[pathlib.Path], schema: pyarrow.Schema | None = None, has_header: bool = True, delimiter: str = ',', schema_infer_max_records: int = DEFAULT_MAX_INFER_SCHEMA, file_extension: str = '.csv', table_partition_cols: list[tuple[str, str | pyarrow.DataType]] | None = None, file_compression_type: str | None = None, options: datafusion.options.CsvReadOptions | None = None, object_store: Any | None = None) datafusion.dataframe.DataFrame#
Read a CSV data source.
- Parameters:
path – Path to the CSV file
schema – An optional schema representing the CSV files. If None, the CSV reader will try to infer it based on data in file.
has_header – Whether the CSV file have a header. If schema inference is run on a file with no headers, default column names are created.
delimiter – An optional column delimiter.
schema_infer_max_records – Maximum number of rows to read from CSV files for schema inference if needed.
file_extension – File extension; only files with this extension are selected for data input.
table_partition_cols – Partition columns.
file_compression_type – File compression type.
options – Set advanced options for CSV reading. This cannot be combined with any of the other options in this method.
object_store – A pre-configured object store instance to use for accessing the file. When provided, the store is automatically registered for the URL scheme and host parsed from
path.
- Returns:
DataFrame representation of the read CSV files
- read_empty() datafusion.dataframe.DataFrame#
Create an empty
DataFramewith no columns or rows.See also
This is an alias for
empty_table().
- read_json(path: str | pathlib.Path, schema: pyarrow.Schema | None = None, schema_infer_max_records: int = 1000, file_extension: str = '.json', table_partition_cols: list[tuple[str, str | pyarrow.DataType]] | None = None, file_compression_type: str | None = None, object_store: Any | None = None) datafusion.dataframe.DataFrame#
Read a line-delimited JSON data source.
- Parameters:
path – Path to the JSON file.
schema – The data source schema.
schema_infer_max_records – Maximum number of rows to read from JSON files for schema inference if needed.
file_extension – File extension; only files with this extension are selected for data input.
table_partition_cols – Partition columns.
file_compression_type – File compression type.
object_store – A pre-configured object store instance to use for accessing the file. When provided, the store is automatically registered for the URL scheme and host parsed from
path.
- Returns:
DataFrame representation of the read JSON files.
- read_parquet(path: str | pathlib.Path, table_partition_cols: list[tuple[str, str | pyarrow.DataType]] | None = None, parquet_pruning: bool = True, file_extension: str = '.parquet', skip_metadata: bool = True, schema: pyarrow.Schema | None = None, file_sort_order: collections.abc.Sequence[collections.abc.Sequence[datafusion.expr.SortKey]] | None = None, object_store: Any | None = None) datafusion.dataframe.DataFrame#
Read a Parquet source into a
Dataframe.- Parameters:
path – Path to the Parquet file.
table_partition_cols – Partition columns.
parquet_pruning – Whether the parquet reader should use the predicate to prune row groups.
file_extension – File extension; only files with this extension are selected for data input.
skip_metadata – Whether the parquet reader should skip any metadata that may be in the file schema. This can help avoid schema conflicts due to metadata.
schema – An optional schema representing the parquet files. If None, the parquet reader will try to infer it based on data in the file.
file_sort_order – Sort order for the file. Each sort key can be specified as a column name (
str), an expression (Expr), or aSortExpr.object_store – A pre-configured object store instance (e.g.
AmazonS3,GoogleCloud,MicrosoftAzure) to use for accessing the file. When provided, the store is automatically registered for the URL scheme and host parsed frompath, removing the need to callregister_object_store()separately. This is especially useful in multi-threaded environments where setting credentials viaos.environis not thread-safe.
- Returns:
DataFrame representation of the read Parquet files
Examples
Read a local Parquet file:
>>> import datafusion >>> ctx = datafusion.SessionContext() >>> df = ctx.read_parquet("data.parquet")
Read from S3 with inline credentials (thread-safe):
>>> from datafusion.object_store import AmazonS3 >>> store = AmazonS3( ... bucket_name="my-bucket", ... region="us-east-1", ... access_key_id="...", ... secret_access_key="...", ... ) >>> df = ctx.read_parquet( ... "s3://my-bucket/data.parquet", ... object_store=store, ... )
- read_table(table: datafusion.catalog.Table | TableProviderExportable | datafusion.dataframe.DataFrame | pyarrow.dataset.Dataset) datafusion.dataframe.DataFrame#
Creates a
DataFramefrom a table.
- refresh_catalogs() None#
Refresh catalog metadata.
Examples
>>> ctx = SessionContext() >>> ctx.refresh_catalogs()
- register_arrow(name: str, path: str | pathlib.Path, schema: pyarrow.Schema | None = None, file_extension: str = '.arrow', table_partition_cols: list[tuple[str, str | pyarrow.DataType]] | None = None, object_store: Any | None = None) None#
Register an Arrow IPC file as a table.
The registered table can be referenced from SQL statements executed against this context.
- Parameters:
name – Name of the table to register.
path – Path to the Arrow IPC file.
schema – The data source schema.
file_extension – File extension to select.
table_partition_cols – Partition columns.
object_store – A pre-configured object store instance to use for accessing the file. When provided, the store is automatically registered for the URL scheme and host parsed from
path.
Examples
>>> import tempfile, os >>> ctx = dfn.SessionContext() >>> table = pa.table({"x": [10, 20, 30]}) >>> with tempfile.TemporaryDirectory() as tmpdir: ... path = os.path.join(tmpdir, "data.arrow") ... with pa.ipc.new_file(path, table.schema) as writer: ... writer.write_table(table) ... ctx.register_arrow("arrow_tbl", path) ... ctx.sql("SELECT * FROM arrow_tbl").collect()[0].column(0) <pyarrow.lib.Int64Array object at ...> [ 10, 20, 30 ]
Provide an explicit
schemato override schema inference:>>> with tempfile.TemporaryDirectory() as tmpdir: ... path = os.path.join(tmpdir, "data.arrow") ... with pa.ipc.new_file(path, table.schema) as writer: ... writer.write_table(table) ... ctx.register_arrow( ... "arrow_schema", ... path, ... schema=pa.schema([("x", pa.int64())]), ... ) ... ctx.sql("SELECT * FROM arrow_schema").collect()[0].column(0) <pyarrow.lib.Int64Array object at ...> [ 10, 20, 30 ]
Use
file_extensionto read files with a non-default extension:>>> with tempfile.TemporaryDirectory() as tmpdir: ... path = os.path.join(tmpdir, "data.ipc") ... with pa.ipc.new_file(path, table.schema) as writer: ... writer.write_table(table) ... ctx.register_arrow( ... "arrow_ipc", path, file_extension=".ipc" ... ) ... ctx.sql("SELECT * FROM arrow_ipc").collect()[0].column(0) <pyarrow.lib.Int64Array object at ...> [ 10, 20, 30 ]
- register_avro(name: str, path: str | pathlib.Path, schema: pyarrow.Schema | None = None, file_extension: str = '.avro', table_partition_cols: list[tuple[str, str | pyarrow.DataType]] | None = None, object_store: Any | None = None) None#
Register an Avro file as a table.
The registered table can be referenced from SQL statement executed against this context.
- Parameters:
name – Name of the table to register.
path – Path to the Avro file.
schema – The data source schema.
file_extension – File extension to select.
table_partition_cols – Partition columns.
object_store – A pre-configured object store instance to use for accessing the file. When provided, the store is automatically registered for the URL scheme and host parsed from
path.
- register_batch(name: str, batch: pyarrow.RecordBatch) None#
Register a single
pa.RecordBatchas a table.- Parameters:
name – Name of the resultant table.
batch – Record batch to register as a table.
Examples
>>> ctx = dfn.SessionContext() >>> batch = pa.RecordBatch.from_pydict({"a": [1, 2, 3]}) >>> ctx.register_batch("batch_tbl", batch) >>> ctx.sql("SELECT * FROM batch_tbl").collect()[0].column(0) <pyarrow.lib.Int64Array object at ...> [ 1, 2, 3 ]
- register_catalog_provider(name: str, provider: datafusion.catalog.CatalogProviderExportable | datafusion.catalog.CatalogProvider | datafusion.catalog.Catalog) None#
Register a catalog provider.
- register_catalog_provider_list(provider: datafusion.catalog.CatalogProviderListExportable | datafusion.catalog.CatalogProviderList | datafusion.catalog.CatalogList) None#
Register a catalog provider list.
- register_csv(name: str, path: str | pathlib.Path | list[str | pathlib.Path], schema: pyarrow.Schema | None = None, has_header: bool = True, delimiter: str = ',', schema_infer_max_records: int = DEFAULT_MAX_INFER_SCHEMA, file_extension: str = '.csv', file_compression_type: str | None = None, options: datafusion.options.CsvReadOptions | None = None, object_store: Any | None = None) None#
Register a CSV file as a table.
The registered table can be referenced from SQL statement executed against.
- Parameters:
name – Name of the table to register.
path – Path to the CSV file. It also accepts a list of Paths.
schema – An optional schema representing the CSV file. If None, the CSV reader will try to infer it based on data in file.
has_header – Whether the CSV file have a header. If schema inference is run on a file with no headers, default column names are created.
delimiter – An optional column delimiter.
schema_infer_max_records – Maximum number of rows to read from CSV files for schema inference if needed.
file_extension – File extension; only files with this extension are selected for data input.
file_compression_type – File compression type.
options – Set advanced options for CSV reading. This cannot be combined with any of the other options in this method.
object_store – A pre-configured object store instance to use for accessing the file. When provided, the store is automatically registered for the URL scheme and host parsed from
path.
- register_dataset(name: str, dataset: pyarrow.dataset.Dataset) None#
Register a
pa.dataset.Datasetas a table.- Parameters:
name – Name of the table to register.
dataset – PyArrow dataset.
- register_json(name: str, path: str | pathlib.Path, schema: pyarrow.Schema | None = None, schema_infer_max_records: int = 1000, file_extension: str = '.json', table_partition_cols: list[tuple[str, str | pyarrow.DataType]] | None = None, file_compression_type: str | None = None, object_store: Any | None = None) None#
Register a JSON file as a table.
The registered table can be referenced from SQL statement executed against this context.
- Parameters:
name – Name of the table to register.
path – Path to the JSON file.
schema – The data source schema.
schema_infer_max_records – Maximum number of rows to read from JSON files for schema inference if needed.
file_extension – File extension; only files with this extension are selected for data input.
table_partition_cols – Partition columns.
file_compression_type – File compression type.
object_store – A pre-configured object store instance to use for accessing the file. When provided, the store is automatically registered for the URL scheme and host parsed from
path.
- register_listing_table(name: str, path: str | pathlib.Path, table_partition_cols: list[tuple[str, str | pyarrow.DataType]] | None = None, file_extension: str = '.parquet', schema: pyarrow.Schema | None = None, file_sort_order: collections.abc.Sequence[collections.abc.Sequence[datafusion.expr.SortKey]] | None = None) None#
Register multiple files as a single table.
Registers a
Tablethat can assemble multiple files from locations in anObjectStoreinstance.- Parameters:
name – Name of the resultant table.
path – Path to the file to register.
table_partition_cols – Partition columns.
file_extension – File extension of the provided table.
schema – The data source schema.
file_sort_order – Sort order for the file. Each sort key can be specified as a column name (
str), an expression (Expr), or aSortExpr.
- register_object_store(schema: str, store: Any, host: str | None = None) None#
Add a new object store into the session.
- Parameters:
schema – The data source schema.
store – The
ObjectStoreto register.host – URL for the host.
- register_parquet(name: str, path: str | pathlib.Path, table_partition_cols: list[tuple[str, str | pyarrow.DataType]] | None = None, parquet_pruning: bool = True, file_extension: str = '.parquet', skip_metadata: bool = True, schema: pyarrow.Schema | None = None, file_sort_order: collections.abc.Sequence[collections.abc.Sequence[datafusion.expr.SortKey]] | None = None, object_store: Any | None = None) None#
Register a Parquet file as a table.
The registered table can be referenced from SQL statement executed against this context.
- Parameters:
name – Name of the table to register.
path – Path to the Parquet file.
table_partition_cols – Partition columns.
parquet_pruning – Whether the parquet reader should use the predicate to prune row groups.
file_extension – File extension; only files with this extension are selected for data input.
skip_metadata – Whether the parquet reader should skip any metadata that may be in the file schema. This can help avoid schema conflicts due to metadata.
schema – The data source schema.
file_sort_order – Sort order for the file. Each sort key can be specified as a column name (
str), an expression (Expr), or aSortExpr.object_store – A pre-configured object store instance (e.g.
AmazonS3,GoogleCloud,MicrosoftAzure) to use for accessing the file. When provided, the store is automatically registered for the URL scheme and host parsed frompath, removing the need to callregister_object_store()separately. This is especially useful in multi-threaded environments where setting credentials viaos.environis not thread-safe.
Examples
Register a local Parquet file:
>>> import datafusion >>> ctx = datafusion.SessionContext() >>> ctx.register_parquet("my_table", "data.parquet")
Register from S3 with inline credentials (thread-safe):
>>> from datafusion.object_store import AmazonS3 >>> store = AmazonS3( ... bucket_name="my-bucket", ... region="us-east-1", ... access_key_id="...", ... secret_access_key="...", ... ) >>> ctx.register_parquet( ... "my_table", ... "s3://my-bucket/data.parquet", ... object_store=store, ... )
- register_record_batches(name: str, partitions: list[list[pyarrow.RecordBatch]]) None#
Register record batches as a table.
This function will convert the provided partitions into a table and register it into the session using the given name.
- Parameters:
name – Name of the resultant table.
partitions – Record batches to register as a table.
- register_table(name: str, table: datafusion.catalog.Table | TableProviderExportable | datafusion.dataframe.DataFrame | pyarrow.dataset.Dataset) None#
Register a
Tablewith this context.The registered table can be referenced from SQL statements executed against this context.
- Parameters:
name – Name of the resultant table.
table – Any object that can be converted into a
Table.
- register_table_factory(format: str, factory: datafusion.catalog.TableProviderFactory | datafusion.catalog.TableProviderFactoryExportable) None#
Register a
TableProviderFactoryExportable.The registered factory can be referenced from SQL DDL statements executed against this context.
- Parameters:
format – The value to be used in STORED AS ${format} clause.
factory – A PyCapsule that implements
TableProviderFactoryExportable
- register_table_provider(name: str, provider: datafusion.catalog.Table | TableProviderExportable | datafusion.dataframe.DataFrame | pyarrow.dataset.Dataset) None#
Register a table provider.
Deprecated: use
register_table()instead.
- register_udaf(udaf: datafusion.user_defined.AggregateUDF) None#
Register a user-defined aggregation function (UDAF) with the context.
- register_udf(udf: datafusion.user_defined.ScalarUDF) None#
Register a user-defined function (UDF) with the context.
- register_udtf(func: datafusion.user_defined.TableFunction) None#
Register a user defined table function.
- register_udwf(udwf: datafusion.user_defined.WindowUDF) None#
Register a user-defined window function (UDWF) with the context.
- register_view(name: str, df: datafusion.dataframe.DataFrame) None#
Register a
DataFrameas a view.- Parameters:
name (str) – The name to register the view under.
df (DataFrame) – The DataFrame to be converted into a view and registered.
- remove_optimizer_rule(name: str) bool#
Remove an optimizer rule by name.
- Parameters:
name – Name of the optimizer rule to remove.
- Returns:
True if a rule with the given name was found and removed.
Examples
>>> ctx = SessionContext() >>> ctx.remove_optimizer_rule("nonexistent_rule") False
- session_id() str#
Return an id that uniquely identifies this
SessionContext.
- session_start_time() str#
Return the session start time as an RFC 3339 formatted string.
Examples
>>> ctx = SessionContext() >>> ctx.session_start_time() '2026-01-01T12:34:56.123456789+00:00'
- set_query_planner(planner: datafusion.extensions.QueryPlannerExportable | types.CapsuleType) None#
Install a custom query planner on this session.
The planner is imported through its
__datafusion_query_planner__PyCapsule, in the same wayadd_physical_optimizer_rule()installs a rule.Returns nothing, because the planner lives in the session rather than in a handle on it — installing one is visible to every context sharing that session, including ones an earlier
with_*call returned. SeeSessionContext.A session holds exactly one planner, so calling this again replaces the previous one rather than layering. To chain planners, have the new planner wrap the capsule from
__datafusion_query_planner__(), captured before the new planner is installed.Install any extension codecs before a layered planner; the rebuild that follows a later codec install does not reach the fallback inside one. See Install codecs before a layered planner, or prefer
with_extensions(), which cannot capture a partial chain.- Parameters:
planner – Object exposing
__datafusion_query_planner__(seeQueryPlannerExportable) or a rawdatafusion_query_plannerPyCapsule.- Raises:
ValueError – If the capsule is not named
datafusion_query_planner.
Examples
A session exports its own planner, which is what you capture to wrap:
>>> from datafusion import SessionContext >>> ctx = SessionContext() >>> fallback = ctx.__datafusion_query_planner__() >>> type(fallback).__name__ 'PyCapsule'
Skipped here (needs a built extension library):
>>> from my_extension import DistributedQueryPlanner >>> ctx.set_query_planner( ... DistributedQueryPlanner(fallback=fallback) ... ) >>> ctx.sql("SELECT * FROM remote_table").collect()
- sql(query: str, options: SQLOptions | None = None, param_values: dict[str, Any] | None = None, **named_params: Any) datafusion.dataframe.DataFrame#
Create a
DataFramefrom SQL query text.See the online documentation for a description of how to perform parameterized substitution via either the
param_valuesoption or passing innamed_params.Note: This API implements DDL statements such as
CREATE TABLEandCREATE VIEWand DML statements such asINSERT INTOwith in-memory default implementation.Seesql_with_options().- Parameters:
query – SQL query text.
options – If provided, the query will be validated against these options.
param_values – Provides substitution of scalar values in the query after parsing.
named_params – Provides string or DataFrame substitution in the query string.
- Returns:
DataFrame representation of the SQL query.
- sql_with_options(query: str, options: SQLOptions, param_values: dict[str, Any] | None = None, **named_params: Any) datafusion.dataframe.DataFrame#
Create a
DataFramefrom SQL query text.This function will first validate that the query is allowed by the provided options.
- Parameters:
query – SQL query text.
options – SQL options.
param_values – Provides substitution of scalar values in the query after parsing.
named_params – Provides string or DataFrame substitution in the query string.
- Returns:
DataFrame representation of the SQL query.
- table(name: str) datafusion.dataframe.DataFrame#
Retrieve a previously registered table by name.
- table_exist(name: str) bool#
Return whether a table with the given name exists.
- table_provider(name: str) datafusion.catalog.Table#
Return the
Tablefor the given table name.- Parameters:
name – Name of the table.
- Returns:
The table provider.
- Raises:
KeyError – If the table is not found.
Examples
>>> import pyarrow as pa >>> ctx = SessionContext() >>> batch = pa.RecordBatch.from_pydict({"x": [1, 2]}) >>> ctx.register_record_batches("my_table", [[batch]]) >>> tbl = ctx.table_provider("my_table") >>> tbl.schema x: int64
- udaf(name: str) datafusion.user_defined.AggregateUDF#
Look up a registered aggregate UDF by name.
Returns the same
AggregateUDFwrapper thatregister_udaf()accepts. Built-in aggregate functions such assumoravgare also discoverable through this lookup. Seeudf()for a worked late-binding example; the pattern is identical for aggregates.- Parameters:
name – Name of the registered aggregate UDF.
- Raises:
KeyError – If no aggregate UDF is registered under
name.
Examples
Look up a built-in aggregate by name and use it in
aggregate():>>> ctx = dfn.SessionContext() >>> sum_fn = ctx.udaf("sum") >>> df = ctx.from_pydict({"a": [1, 2, 3]}) >>> df.aggregate([], [sum_fn(col("a")).alias("total")]).to_pydict() {'total': [6]}
- udafs() list[str]#
Return the sorted names of all registered aggregate UDFs.
Examples
>>> ctx = dfn.SessionContext() >>> "sum" in ctx.udafs() True
- udf(name: str) datafusion.user_defined.ScalarUDF#
Look up a registered scalar UDF by name.
Returns the same
ScalarUDFwrapper thatregister_udf()accepts, so it can be invoked as an expression in the DataFrame API or re-registered into a differentSessionContext. Built-in scalar functions from the session’s function registry are also looked up.- Parameters:
name – Name of the registered scalar UDF.
- Raises:
KeyError – If no scalar UDF is registered under
name.
Examples
Register a UDF, then look it up by name and use it in the DataFrame API:
>>> ctx = dfn.SessionContext() >>> nullcheck = dfn.udf( ... lambda x: x.is_null(), ... [pa.int64()], ... pa.bool_(), ... volatility="immutable", ... name="nullcheck", ... ) >>> ctx.register_udf(nullcheck) >>> fn = ctx.udf("nullcheck") >>> df = ctx.from_pydict({"a": [1, None, 3]}) >>> df.select(fn(col("a")).alias("is_null")).to_pydict() {'is_null': [False, True, False]}
Late-binding: the function name can come from configuration rather than an imported symbol, which is useful when the set of UDFs is plugin-driven or chosen at runtime:
>>> config = {"null_check": "nullcheck"} >>> fn = ctx.udf(config["null_check"]) >>> df.select(fn(col("a")).alias("is_null")).to_pydict() {'is_null': [False, True, False]}
- udfs() list[str]#
Return the sorted names of all registered scalar UDFs.
Includes both user-registered and built-in scalar functions. Pair with
udf()to drive discovery, validation, or config-based dispatch.Examples
>>> ctx = dfn.SessionContext() >>> "abs" in ctx.udfs() True
- udwf(name: str) datafusion.user_defined.WindowUDF#
Look up a registered window UDF by name.
Returns the same
WindowUDFwrapper thatregister_udwf()accepts. Built-in window functions such asrow_numberorrankare also discoverable through this lookup. Seeudf()for a worked late-binding example; the pattern is identical for window functions.- Parameters:
name – Name of the registered window UDF.
- Raises:
KeyError – If no window UDF is registered under
name.
Examples
Look up a built-in window function by name and use it in
select:>>> ctx = dfn.SessionContext() >>> rn = ctx.udwf("row_number") >>> df = ctx.from_pydict({"a": [10, 20, 30]}) >>> df.select(col("a"), rn().alias("rn")).to_pydict() {'a': [10, 20, 30], 'rn': [1, 2, 3]}
- udwfs() list[str]#
Return the sorted names of all registered window UDFs.
Examples
>>> ctx = dfn.SessionContext() >>> "row_number" in ctx.udwfs() True
- with_extensions(*extensions: datafusion.extensions.SessionComponentsExportable | datafusion.extensions.SessionPlannerExportable) SessionContext#
Create a new session context with the given extension bundles.
This is the preferred way to install extension codecs and query planners, because it removes the ordering question that installing them by hand creates.
Each argument is called twice, in two phases:
__datafusion_session_components__(ctx)on every extension, then all the returned codecs are installed at once.__datafusion_session_planner__(ctx, fallback)on every extension, in argument order, each handed the planner built so far and the context carrying every bundle’s codecs. The last extension listed ends up outermost.
An extension implements either hook or both. Return
Nonefrom the planner hook to contribute no planner; seeSessionPlannerExportable.Nothing is written to the session until every hook has returned and every capsule has been validated, so a hook that raises leaves the session as it was. A hook that mutates the context it is handed — registering a table, say — is not rolled back, which is why bundle objects must be configuration-only. See Failure and rollback.
Shares its session with this context — see
SessionContext.See Extension bundles in the online documentation for why the phases are split, how to contribute a bundle’s two halves at different positions, and a worked Rust implementation.
- Parameters:
extensions – Extension bundles to install. Order is irrelevant for codecs and significant for planners, which nest in this order with the last one outermost. Passing none installs nothing and returns a handle on this session, so a caller assembling the list at runtime need not special-case it being empty.
- Returns:
A new context with all extension components installed.
- Raises:
TypeError – If an argument implements neither hook, if a hook returns the wrong type, or if a codec is contributed as a bare
PyCapsulerather than an object exposing the getter.ValueError – If two codecs claim the same id, or a getter returns a capsule of the wrong kind. See
with_logical_extension_codec()for how ids are assigned.
Examples
The returned handle is a different object sharing one session, and an empty call is legal:
>>> from datafusion import SessionContext >>> ctx = SessionContext() >>> derived = ctx.with_extensions() >>> derived is ctx False >>> ctx.from_pydict({"a": [1, 2]}, name="t") DataFrame()... >>> derived.table_exist("t") True >>> derived.logical_extension_codec_ids() []
A runnable multi-bundle example, showing what a bundle returns and how its codec ids accumulate, is in Extension bundles.
Real usage. Skipped here (needs a built extension library); run verbatim by
test_with_extensions_docstring_example_still_runs.>>> from my_extension import DistributedEngineExtension >>> ctx = SessionContext().with_extensions( ... DistributedEngineExtension("scheduler:50050") ... ) >>> batches = ctx.sql("SELECT 1 AS n").collect() >>> batches[0].column(0).to_pylist() [1]
- with_logical_extension_codec(codec: datafusion.user_defined.LogicalExtensionCodecExportable | types.CapsuleType, codec_id: str | None = None) SessionContext#
Create a new session context with an additional logical codec.
Only FFI codecs are supported. Pass any object implementing
__datafusion_logical_extension_codec__(seeLogicalExtensionCodecExportable).Codecs compose: each call appends the codec rather than replacing codecs installed earlier, so one session can carry codecs from several independent libraries and the order they are installed in does not affect decoding.
A serialized plan records which codec wrote each payload, as a short id taken from the codec’s class.
Shares its session with this context — see
SessionContext.See Codec ids in the online documentation for how ids are assigned and what an extension codec has to implement, and
with_extensions()for installing a library’s codecs and planner together.- Parameters:
codec – Object implementing
__datafusion_logical_extension_codec__(seeLogicalExtensionCodecExportable), or a rawdatafusion_logical_extension_codecPyCapsule.codec_id – Overrides the id the codec’s payloads are tagged with. Normally unnecessary. Pass it when installing two instances of one class, which otherwise claim the same id, and when installing a bare
PyCapsule: a capsule has no class to take an id from, so it is given a randomanon:id that differs on every install, and plans it encodes can never be decoded elsewhere.
- Returns:
A new context carrying this codec in addition to any already installed.
- Raises:
ValueError – If the resolved id is already installed on this session.
Examples
A context exports its own codec, which stands in here for a real library’s:
>>> from datafusion import SessionContext >>> host = SessionContext() >>> capsule = host.__datafusion_logical_extension_codec__() >>> ctx = SessionContext().with_logical_extension_codec( ... capsule, codec_id="my_library.Codec" ... ) >>> ctx.logical_extension_codec_ids() ['my_library.Codec']
Without
codec_ida bare capsule gets an anonymous id, which is fine only if its plans never leave this session:>>> ctx = SessionContext().with_logical_extension_codec(capsule) >>> ctx.logical_extension_codec_ids()[0].startswith("anon:") True
- with_physical_extension_codec(codec: datafusion.user_defined.PhysicalExtensionCodecExportable | types.CapsuleType, codec_id: str | None = None) SessionContext#
Create a new session context with an additional physical codec.
Only FFI codecs are supported. Pass any object implementing
__datafusion_physical_extension_codec__(seePhysicalExtensionCodecExportable).Composes and assigns an id exactly as
with_logical_extension_codec()does, including when to passcodec_idand what the returned context shares. See that method.- Parameters:
codec – As
with_logical_extension_codec(), for the physical getter.codec_id – As
with_logical_extension_codec().
- Returns:
A new context carrying this codec in addition to any already installed.
- Raises:
ValueError – If the resolved id is already installed on this session.
Examples
>>> from datafusion import SessionContext >>> host = SessionContext() >>> capsule = host.__datafusion_physical_extension_codec__() >>> ctx = SessionContext().with_physical_extension_codec( ... capsule, codec_id="my_library.PhysicalCodec" ... ) >>> ctx.physical_extension_codec_ids() ['my_library.PhysicalCodec']
- with_python_udf_inlining(*, enabled: bool) SessionContext#
Control whether Python UDFs are embedded in serialized expressions.
With
enabled=True, serialized expressions carry the Python code for any scalar, aggregate, or window UDFs they reference. The receiver rebuilds the UDFs from those bytes and does not need to register them first.With
enabled=False, serialized expressions store only the UDF names. This has two uses:Cross-language portability. The bytes can be decoded by a non-Python receiver, which must already have UDFs registered under matching names.
Safer deserialization.
Expr.from_bytes()will refuse to rebuild Python UDFs rather than callcloudpickle.loadson untrusted input.
The setting affects
Expr.to_bytes()andExpr.from_bytes()whenever this session is passed as thectxargument.pickle.dumps()andpickle.loads()do not pass a context, so to apply the setting through pickle, register this session withdatafusion.ipc.set_sender_ctx()on the sender anddatafusion.ipc.set_worker_ctx()on the receiver.Warning
Security This setting narrows only
Expr.from_bytes(). Callingpickle.loads()on untrusted bytes remains unsafe regardless of the toggle.Shares its session with this context — see
SessionContext. The original context’s own codec settings are unchanged.- Parameters:
enabled – Whether to embed Python UDFs in serialized expressions. Keyword-only and required, so callers must pick a mode explicitly. Fresh sessions behave as
enabled=Trueuntil this method overrides the toggle.- Returns:
A new
SessionContextwith the toggle applied.
Examples
>>> import pyarrow as pa >>> from datafusion import SessionContext, Expr, col, udf >>> ctx = SessionContext() >>> identity = udf(lambda a: a, [pa.int64()], pa.int64(), ... volatility="immutable", name="identity_demo") >>> ctx.register_udf(identity) >>> blob = identity(col("x")).to_bytes(ctx) >>> strict = SessionContext().with_python_udf_inlining(enabled=False) >>> try: ... Expr.from_bytes(blob, strict) ... except Exception as e: ... print("Refusing to deserialize" in str(e)) True
- property __datafusion_codec_id__: str#
Identity this context carries when installed as an extension codec.
A context can be installed on another session as an extension codec, which tags the payloads it writes with this string. It is unique per session, so two contexts can be installed on one session and a plan written through one will not be decoded by the other.
Contexts derived from the same session report the same id, so only one of them can be installed on a given session. That is the intended answer: they are one session — see
SessionContext— so their payloads would be indistinguishable on decode.Examples
>>> from datafusion import SessionContext >>> ctx = SessionContext() >>> ctx.__datafusion_codec_id__.startswith("session:") True >>> ctx.__datafusion_codec_id__ == SessionContext().__datafusion_codec_id__ False
- ctx#
- class datafusion.context.TableProviderExportable#
Bases:
ProtocolType hint for object that has __datafusion_table_provider__ PyCapsule.
See Custom Table Provider for registering one, and Providers and catalogs for writing one.
- Parameters:
session – See
LogicalExtensionCodecExportable. For this getter it is a session when the provider is registered throughSessionContext.register_table()and the host’s logical codec when it goes throughdatafusion.catalog.Schema.register_table(), so duck-typing it is not optional.
- __datafusion_table_provider__(session: Any) object#