This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new bbf2d9a1c3 feat(bindings/python): accept dicts for map-valued options
in from_config (#9318)
bbf2d9a1c3 is described below
commit bbf2d9a1c3b2845964cd7dd4225bd6c0710ec06e
Author: Chitral Verma <[email protected]>
AuthorDate: Sat Nov 28 21:18:30 2026 +0530
feat(bindings/python): accept dicts for map-valued options in from_config
(#9318)
* feat(bindings/python): accept dicts for map-valued options in from_config
Operator.from_config and AsyncOperator.from_config now lower a dict with
str keys and values to the JSON object string core parses for map
options such as S3Config.assume_role_session_tags and
HdfsNativeConfig.options. Keys are sorted, {} stays an explicit empty
object, and non-str members, dicts inside lists or tuples, and other
mappings still raise Unsupported.
Signed-off-by: Chitral Verma <[email protected]>
* fix(bindings/python): convert dicts only for map-valued service options
Signed-off-by: Chitral Verma <[email protected]>
* fix(bindings/python): regenerate stubs and shorten a test docstring
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
bindings/python/Cargo.toml | 1 +
bindings/python/python/opendal/operator.pyi | 16 ++--
bindings/python/src/operator.rs | 51 ++++++++--
bindings/python/src/services.rs | 13 +++
bindings/python/tests/test_from_config.py | 142 +++++++++++++++++++++++++++-
dev/src/generate/python.j2 | 13 +++
dev/src/generate/python.rs | 24 ++++-
7 files changed, 242 insertions(+), 18 deletions(-)
diff --git a/bindings/python/Cargo.toml b/bindings/python/Cargo.toml
index 72894e3a88..feb8941075 100644
--- a/bindings/python/Cargo.toml
+++ b/bindings/python/Cargo.toml
@@ -279,6 +279,7 @@ pyo3 = { version = "0.30.1", features = [
"jiff-02",
] }
pyo3-async-runtimes = { version = "0.30.0", features = ["tokio-runtime"] }
+serde_json = "1"
tokio = "1"
[profile.release]
diff --git a/bindings/python/python/opendal/operator.pyi
b/bindings/python/python/opendal/operator.pyi
index 798dd7d8b3..983de22e62 100644
--- a/bindings/python/python/opendal/operator.pyi
+++ b/bindings/python/python/opendal/operator.pyi
@@ -221,9 +221,11 @@ class AsyncOperator:
A static type checker validates the service scheme and the options for
the service, context, and layers. The binding converts non-string
values
such as booleans, integers, finite floats, durations, paths, and flat
- lists or tuples to the strings the registry consumes.
- Service config values such as bytes, mappings, and nested sequences
- raise ``Unsupported``.
+ lists or tuples to the strings the registry consumes. For a service
+ option that takes a map, such as ``S3Config.assume_role_session_tags``,
+ a ``dict`` with ``str`` keys and values becomes a JSON object string.
+ A ``dict`` for any other option, and values such as bytes, other
+ mappings, and nested sequences, raise ``Unsupported``.
Construction options are stored when pickling the operator and may
include credentials. Reapply layers added via ``.layer()`` after
unpickling.
@@ -990,9 +992,11 @@ class Operator:
A static type checker validates the service scheme and the options for
the service, context, and layers. The binding converts non-string
values
such as booleans, integers, finite floats, durations, paths, and flat
- lists or tuples to the strings the registry consumes.
- Service config values such as bytes, mappings, and nested sequences
- raise ``Unsupported``.
+ lists or tuples to the strings the registry consumes. For a service
+ option that takes a map, such as ``S3Config.assume_role_session_tags``,
+ a ``dict`` with ``str`` keys and values becomes a JSON object string.
+ A ``dict`` for any other option, and values such as bytes, other
+ mappings, and nested sequences, raise ``Unsupported``.
Construction options are stored when pickling the operator and may
include credentials. Reapply layers added via ``.layer()`` after
unpickling.
diff --git a/bindings/python/src/operator.rs b/bindings/python/src/operator.rs
index 45555c399e..7136520a46 100644
--- a/bindings/python/src/operator.rs
+++ b/bindings/python/src/operator.rs
@@ -15,6 +15,7 @@
// specific language governing permissions and limitations
// under the License.
+use std::collections::BTreeMap;
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::Duration;
@@ -180,7 +181,7 @@ fn config_scalar_to_string(value: &Bound<PyAny>) ->
PyResult<String> {
Ok(format!("{micros}us"))
} else if value.cast::<PyDict>().is_ok() {
Err(Unsupported::new_err(
- "a map-valued config field cannot be built via from_config; leave
it unset",
+ "a dict config value is accepted only for a service's map-valued
options, such as S3Config.assume_role_session_tags",
))
} else if value.hasattr(pyo3::intern!(py, "__fspath__"))? {
let fspath = py
@@ -201,13 +202,34 @@ fn config_scalar_to_string(value: &Bound<PyAny>) ->
PyResult<String> {
}
}
+/// Convert a `dict` given for a service's map-valued option into the JSON
+/// object string core parses for map options. Keys are sorted so equal dicts
+/// store the same string.
+fn config_map_to_json(dict: &Bound<PyDict>) -> PyResult<String> {
+ let mut map = BTreeMap::new();
+ for (key, value) in dict.iter() {
+ let (Ok(key), Ok(value)) = (key.extract::<String>(),
value.extract::<String>()) else {
+ return Err(Unsupported::new_err(
+ "a dict config value must map str keys to str values",
+ ));
+ };
+ // Only reachable with `str` subclasses whose `__eq__`/`__hash__`
+ // differ from their string content.
+ if map.insert(key, value).is_some() {
+ return Err(ConfigInvalid::new_err("a dict config value repeats a
key"));
+ }
+ }
+ serde_json::to_string(&map).map_err(|e| Unexpected::new_err(e.to_string()))
+}
+
/// Convert a config value into the string form core's config deserializer
/// consumes.
///
/// Accepts the native types the `opendal.config` TypedDicts declare: `str`,
/// `bool`, `int`, finite `float`, `datetime.timedelta`, `os.PathLike[str]`,
/// and flat `list`/`tuple` of those (`,`-joined, as core parses `Vec`). Nested
-/// collections and mappings have no flat-map form and are rejected.
+/// collections and mappings have no flat-map form and are rejected; a
service's
+/// map-valued options go through [`config_map_to_json`] instead.
fn config_value_to_string(value: &Bound<PyAny>) -> PyResult<String> {
if let Ok(list) = value.cast::<PyList>() {
let parts = list
@@ -245,11 +267,18 @@ fn extract_typed_config(
.ok_or_else(|| Unsupported::new_err("config is missing the required
'scheme' key"))?
.extract::<String>()?;
+ // Core matches the scheme and option keys case-insensitively.
+ let map_fields =
crate::services::map_config_fields(&scheme.to_ascii_lowercase());
let mut map = HashMap::with_capacity(dict.len());
for (k, v) in dict.iter() {
let key = k.extract::<String>()?;
if key != "scheme" {
- let value = config_value_to_string(&v)?;
+ let value = match v.cast::<PyDict>() {
+ Ok(field) if
map_fields.contains(&key.to_ascii_lowercase().as_str()) => {
+ config_map_to_json(field)?
+ }
+ _ => config_value_to_string(&v)?,
+ };
map.insert(key, value);
}
}
@@ -449,9 +478,11 @@ impl Operator {
/// A static type checker validates the service scheme and the options for
/// the service, context, and layers. The binding converts non-string
values
/// such as booleans, integers, finite floats, durations, paths, and flat
- /// lists or tuples to the strings the registry consumes.
- /// Service config values such as bytes, mappings, and nested sequences
- /// raise ``Unsupported``.
+ /// lists or tuples to the strings the registry consumes. For a service
+ /// option that takes a map, such as ``S3Config.assume_role_session_tags``,
+ /// a ``dict`` with ``str`` keys and values becomes a JSON object string.
+ /// A ``dict`` for any other option, and values such as bytes, other
+ /// mappings, and nested sequences, raise ``Unsupported``.
///
/// Construction options are stored when pickling the operator and may
/// include credentials. Reapply layers added via ``.layer()`` after
unpickling.
@@ -1375,9 +1406,11 @@ impl AsyncOperator {
/// A static type checker validates the service scheme and the options for
/// the service, context, and layers. The binding converts non-string
values
/// such as booleans, integers, finite floats, durations, paths, and flat
- /// lists or tuples to the strings the registry consumes.
- /// Service config values such as bytes, mappings, and nested sequences
- /// raise ``Unsupported``.
+ /// lists or tuples to the strings the registry consumes. For a service
+ /// option that takes a map, such as ``S3Config.assume_role_session_tags``,
+ /// a ``dict`` with ``str`` keys and values becomes a JSON object string.
+ /// A ``dict`` for any other option, and values such as bytes, other
+ /// mappings, and nested sequences, raise ``Unsupported``.
///
/// Construction options are stored when pickling the operator and may
/// include credentials. Reapply layers added via ``.layer()`` after
unpickling.
diff --git a/bindings/python/src/services.rs b/bindings/python/src/services.rs
index 7e7bb19e76..f88db75a2a 100644
--- a/bindings/python/src/services.rs
+++ b/bindings/python/src/services.rs
@@ -393,3 +393,16 @@ impl_enum_to_str!(
YandexDisk => "yandex-disk",
}
);
+
+/// Return the config fields of `scheme` that core reads as a map from a JSON
+/// object string. `from_config` converts a `dict` to that string only for
+/// these fields.
+pub(crate) fn map_config_fields(scheme: &str) -> &'static [&'static str] {
+ match scheme {
+ #[cfg(feature = "services-hdfs-native")]
+ "hdfs-native" => &["options"],
+ #[cfg(feature = "services-s3")]
+ "s3" => &["assume_role_session_tags"],
+ _ => &[],
+ }
+}
diff --git a/bindings/python/tests/test_from_config.py
b/bindings/python/tests/test_from_config.py
index 364ae4ad5e..c629903ce5 100644
--- a/bindings/python/tests/test_from_config.py
+++ b/bindings/python/tests/test_from_config.py
@@ -15,6 +15,7 @@
# specific language governing permissions and limitations
# under the License.
+import json
import pickle
from collections import UserDict
from datetime import timedelta
@@ -27,12 +28,13 @@ import opendal
from opendal.config import (
ConcurrentLimitLayerConfig,
FsConfig,
+ HdfsNativeConfig,
MiniMokaConfig,
MokaConfig,
RetryLayerConfig,
S3Config,
)
-from opendal.exceptions import ConfigInvalid, Unsupported
+from opendal.exceptions import ConfigInvalid, Unexpected, Unsupported
@pytest.mark.need_capability("shared")
@@ -144,6 +146,142 @@ def test_from_config_stringifies_flat_list_and_tuple():
assert args[1]["probe_tuple"] == "x,1,true,/p,1000000us"
+def _s3_with_tags(tags: object) -> S3Config:
+ """Build an offline S3 config with `tags` as `assume_role_session_tags`."""
+ return {
+ "scheme": "s3",
+ "bucket": "b",
+ "region": "us-east-1",
+ "assume_role_session_tags": tags,
+ } # type: ignore[typeddict-item, return-value]
+
+
[email protected]("operator_type", [opendal.Operator,
opendal.AsyncOperator])
+def test_from_config_lowers_map_option_dict_to_json_object(operator_type):
+ op = operator_type.from_config(
+ _s3_with_tags({"fs.defaultFS": "hdfs://ns", "Team": "a,b=c"})
+ )
+ _, args = op.__reduce__()
+ assert (
+ args[1]["assume_role_session_tags"]
+ == '{"Team":"a,b=c","fs.defaultFS":"hdfs://ns"}'
+ )
+
+
+def test_from_config_map_option_values_survive_json_encoding():
+ value = {'quote"': "back\\slash", "newline": "a\nb", "control": "\x01",
"ü": "ß"}
+ op = opendal.Operator.from_config(_s3_with_tags(value))
+ _, args = op.__reduce__()
+ assert json.loads(args[1]["assume_role_session_tags"]) == value
+
+
+def test_from_config_empty_map_option_dict_is_explicit_empty_object():
+ op = opendal.Operator.from_config(_s3_with_tags({}))
+ _, args = op.__reduce__()
+ assert args[1]["assume_role_session_tags"] == "{}"
+
+
[email protected]("operator_type", [opendal.Operator,
opendal.AsyncOperator])
+def test_from_config_rejects_dict_for_non_map_option(operator_type):
+ # `fs.root` is a string option, so a dict must not reach the service as a
+ # JSON string (it would become a directory named `{"directory":"data"}`).
+ with pytest.raises(Unsupported, match="map-valued options"):
+ operator_type.from_config(
+ {"scheme": "fs", "root": {"directory": "data"}} # type:
ignore[typeddict-item]
+ )
+
+
[email protected]("operator_type", [opendal.Operator,
opendal.AsyncOperator])
+def test_from_config_rejects_dict_for_context_and_layer_options(operator_type):
+ with pytest.raises(Unsupported, match="map-valued options"):
+ operator_type.from_config(
+ {"scheme": "memory"},
+ context={"http": {"proxy": {"url": "http://proxy"}}}, # type:
ignore[dict-item]
+ )
+ with pytest.raises(Unsupported, match="map-valued options"):
+ operator_type.from_config(
+ {"scheme": "memory"},
+ layers=[{"name": "retry", "factor": {"a": "1"}}], # type:
ignore[list-item]
+ )
+
+
[email protected](
+ "bad_tags",
+ [
+ {"a": 1},
+ {1: "a"},
+ {"a": None},
+ {"a": {"b": "c"}},
+ {"a": ["x"]},
+ {"a": b"x"},
+ ],
+)
+def test_from_config_rejects_map_option_dict_with_non_str_members(bad_tags):
+ with pytest.raises(Unsupported, match="must map str keys to str values"):
+ opendal.Operator.from_config(_s3_with_tags(bad_tags))
+
+
+class IdentityKey(str):
+ """A str subclass whose equal-content instances are distinct dict keys."""
+
+ __hash__ = object.__hash__
+
+ def __eq__(self, other: object) -> bool:
+ """Compare by identity."""
+ return self is other
+
+
+def test_from_config_rejects_dict_keys_with_equal_content():
+ value = {IdentityKey("Team"): "a", IdentityKey("Team"): "b"}
+ assert len(value) == 2
+ with pytest.raises(ConfigInvalid, match="repeats a key"):
+ opendal.Operator.from_config(_s3_with_tags(value))
+
+
[email protected]("operator_type", [opendal.Operator,
opendal.AsyncOperator])
+def test_from_config_s3_session_tags_from_dict(operator_type):
+ op = operator_type.from_config(
+ S3Config(
+ scheme="s3",
+ bucket="b",
+ region="us-east-1",
+ assume_role_session_tags={"Team": "x"},
+ )
+ )
+ _, args = op.__reduce__()
+ assert args[1]["assume_role_session_tags"] == '{"Team":"x"}'
+ if operator_type is opendal.Operator:
+ restored = pickle.loads(pickle.dumps(op))
+ _, restored_args = restored.__reduce__()
+ assert restored_args[1]["assume_role_session_tags"] == '{"Team":"x"}'
+
+
[email protected](
+ not hasattr(opendal.services.Scheme, "HdfsNative"),
+ reason="requires the services-hdfs-native feature",
+)
+def test_from_config_hdfs_native_options_keep_key_case():
+ # With `name_node="default"`, the hdfs-native client reads `fs.defaultFS`
+ # from `options` while building, without contacting a NameNode.
+ opendal.Operator.from_config(
+ HdfsNativeConfig(
+ scheme="hdfs-native",
+ name_node="default",
+ root="/tmp",
+ options={"fs.defaultFS": "hdfs://127.0.0.1:9000"},
+ )
+ )
+ with pytest.raises(Unexpected, match="No fs.defaultFS setting found"):
+ opendal.Operator.from_config(
+ HdfsNativeConfig(
+ scheme="hdfs-native",
+ name_node="default",
+ root="/tmp",
+ options={"fs.defaultfs": "hdfs://127.0.0.1:9000"},
+ )
+ )
+
+
class BytesPathLike:
def __fspath__(self) -> bytes:
"""Return a bytes path."""
@@ -165,6 +303,8 @@ def _make_cyclic_list() -> list[object]:
memoryview(b"/tmp/foo"),
BytesPathLike(),
{"a": "1"},
+ [{"a": "1"}],
+ ({"a": "1"},),
MappingProxyType({"a": "1", "b": "2"}),
UserDict({"a": "1"}),
{"a", "b"},
diff --git a/dev/src/generate/python.j2 b/dev/src/generate/python.j2
index 21227fed69..938af640ec 100644
--- a/dev/src/generate/python.j2
+++ b/dev/src/generate/python.j2
@@ -81,3 +81,16 @@ impl_enum_to_str!(
{%- endfor %}
}
);
+
+/// Return the config fields of `scheme` that core reads as a map from a JSON
+/// object string. `from_config` converts a `dict` to that string only for
+/// these fields.
+pub(crate) fn map_config_fields(scheme: &str) -> &'static [&'static str] {
+ match scheme {
+{%- for item in map_fields %}
+ #[cfg(feature = "{{ service_to_feature(item[0]) }}")]
+ "{{ snake_to_kebab_case(item[0]) }}" => &[{% for field in item[1]
%}"{{ field }}"{% if not loop.last %}, {% endif %}{% endfor %}],
+{%- endfor %}
+ _ => &[],
+ }
+}
diff --git a/dev/src/generate/python.rs b/dev/src/generate/python.rs
index aba55caaa4..9920f1b656 100644
--- a/dev/src/generate/python.rs
+++ b/dev/src/generate/python.rs
@@ -185,10 +185,30 @@ pub fn generate(workspace_dir: PathBuf, services:
Services) -> Result<()> {
env.add_function("make_config_field_doc", make_config_field_doc);
env.add_function("config_field_is_required", config_field_is_required);
- // Generate the `Scheme` enum (Rust).
+ // Map-valued config fields per service. `from_config` converts a dict to
+ // a JSON object string only for these fields. `Services` is a `HashMap`,
+ // so sort by service name to keep the generated file stable.
+ let mut map_fields: Vec<(String, Vec<String>)> = srvs
+ .iter()
+ .filter_map(|(name, srv)| {
+ let fields: Vec<String> = srv
+ .config
+ .iter()
+ .filter(|config| config.value == ConfigType::HashMap)
+ .map(|config| config.name.clone())
+ .collect();
+ (!fields.is_empty()).then(|| (name.clone(), fields))
+ })
+ .collect();
+ map_fields.sort();
+
+ // Generate the `Scheme` enum and the map-field lookup (Rust).
let tmpl = env.get_template("python")?;
let output = workspace_dir.join("bindings/python/src/services.rs");
- let mut rendered = tmpl.render(context! { srvs => Serde(&srvs) })?;
+ let mut rendered = tmpl.render(context! {
+ srvs => Serde(&srvs),
+ map_fields => Serde(&map_fields),
+ })?;
if !rendered.ends_with('\n') {
rendered.push('\n');
}