Stream: helpdesk (published)

Topic: ✔ PythonCall: Handling possibly None value


view this post on Zulip Jesper Stemann Andersen (Apr 18 2023 at 17:02):

How to handle a Py value which can be None (with PythonCall)?

The following seems quite verbose (and it fails if x is an ndarray)

using PythonCall

function handle_optional_value(x::Py)
    if pyconvert(Bool, x == pybuiltins.None)
        return nothing
    end
    # something else
end

view this post on Zulip Santtu (Apr 19 2023 at 04:20):

I do not think that is verbose at all. There is a difference between being succinct and being so truncated as to be illegible. There seems to be an undue respect towards the latter, in many cases.

view this post on Zulip Santtu (Apr 19 2023 at 04:28):

Also, you should probably be using the pyis function from the PythonCall library instead of ==, to compare x to None (link).

view this post on Zulip jar (Apr 19 2023 at 05:03):

function then(f, x::Py)
    if pyconvert(Bool, x == pybuiltins.None)
        return nothing
    end
   f(x)
end

then(y) do x
   x + 1
end

view this post on Zulip Notification Bot (Apr 19 2023 at 09:18):

Jesper Stemann Andersen has marked this topic as resolved.

view this post on Zulip Jesper Stemann Andersen (Apr 19 2023 at 09:19):

Santtu said:

Also, you should probably be using the pyis function from the PythonCall library instead of ==, to compare x to None (link).

Thanks - this was what I was looking for.


Last updated: Nov 06 2024 at 04:40 UTC