Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Build KwArgs for function call in embedded #5241

Unanswered
subatiq asked this question in Q&A
Discussion options

I'm stuck on trying to build KwArgs or PyDict to pass to function call. In python module I have

def run(**kwargs) -> None:
    pass

kwargs are all strings. I try to call it from Rust:

interpreter.enter(move |vm| {
            let module = vm.import("main", 0).unwrap();
            module.get_attr("run", vm).unwrap().call(config, vm);

        });

config initially has type HashMap<String, String>, though I've tried converting it into IndexMap to then build KwArgs from it. The closest I've got is

struct ConfigArg(HashMap<String, String>);

impl Into<KwArgs> for ConfigArg {
    fn into(self) -> KwArgs {
        let mut map = IndexMap::new();

        let mut args = ArgMapping::
        for (key, value) in self.0 {
            let value = PyStr::from(value);
            map.insert(key, value);
        }

        KwArgs::new(map)
    }
}

The problem above is that KwArgs::new(...) expects IndexMap<String, PyObjectRef> and after reading docs I'm still not sure how to achieve this.

You must be logged in to vote

Replies: 1 comment

Comment options

For constants, probably FromIterator will be the easiest way to build it. https://docs.rs/rustpython-vm/latest/rustpython_vm/function/struct.KwArgs.html#impl-FromIterator%3C(String,+T)%3E-for-KwArgs%3CT%3E

let kwargs: KwArgs = [
    ("a".to_owned(), vm.new_pyobj("v1".to_owned()),
    ("b".to_owned(), vm.new_pyobj("v2".to_owned()),
].into_iter().collect();

Otherwise, building IndexMap will be also possible. Don't forget to convert String to PyObejctRef.

impl Into<KwArgs> for ConfigArg {
    fn into(self) -> KwArgs {
        let mut map = IndexMap::new();
        for (key, value) in self.0 {
            let value = vm.new_pyobj(value);  // or `vm.ctx.new_str(value).into()`
            map.insert(key, value);
        }
        KwArgs::new(map)
    }
}
You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
🙏
Q&A
Labels
None yet
2 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.