Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add get method to py::dict #1513

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

woodychow
Copy link

It works just like Python except that the default argument is not optional

@jagerman
Copy link
Member

jagerman commented Sep 9, 2018

I'm sort of ambivalent about including this (the C++ isn't onerous: py::object o = dict.contains(key) ? dict[key] : py::cast(default);, but I think that if we accepted it it would make more sense to move this to class accessor, something along the lines of:

    template <typename T>
    object get_with_default(T &&defaultv) const {
        return obj.contains(key) ? *this : object_or_cast(std::forward<T>(defaultv));
    }

(Then you can use it for non-dict objects--include dicts that are held in C++ objects--as well).

@woodychow
Copy link
Author

boost::python has the same function. I want to minimize the changes needed to transition from boost::python to pybind11. Also, it seems more intuitive to just mirror the existing Python function name and usage.

Could you please elaborate more on the code you wrote? What would be the example usage of it? Is it like

py::accessor(obj, key).get_with_default(defaultv)

?

@jagerman
Copy link
Member

accessor is an internal class that a pybind user should never need to deal with directly, but is the return type of operator [] on a py::object (including py::dict). So in other words, it would allow you to write:

    py::object o = /* ... */;
    py::object val = o["abc"].get_with_default("z");

@woodychow
Copy link
Author

Thanks. I see.

The point of this MR is to mirror the existing Python and boost::python API, which I think is more intuitive than inventing a new API.

@Skylion007
Copy link
Collaborator

Alternative to #2779

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants