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

Don't accept str in FromPyObject for Vec<&str> and Vec<String> #2342

Closed
davidhewitt opened this issue Apr 27, 2022 Discussed in #2341 · 1 comment · Fixed by #2500
Closed

Don't accept str in FromPyObject for Vec<&str> and Vec<String> #2342

davidhewitt opened this issue Apr 27, 2022 Discussed in #2341 · 1 comment · Fixed by #2500

Comments

@davidhewitt
Copy link
Member

As per the title, it would be nice if we didn't accept Python str in FromPyObject for Vec<&str> and Vec<String>. Some background below.

I'm not sure how hard this will be (without specialization).

Discussed in #2341

Originally posted by atoav April 27, 2022
In python one can iterate over a str as if it was a List[str]. And while this is occasionaly useful it can also be a major footgun if users pass in a "string" instead of a ["string"] and suddenly have a function operate on single characters instead of the whole string, as they might (admittedly, errouniously) assumed one that one string.

In python I'd prevent this user error by ensuring incoming str are never treated as a list of characters by wrapping a lone str in a list as follows:

if isinstance(strings, str):
    strings = [strings]

In pyo3 this is an issue as well. Let's say i have a simple function that should take a Vec<String> and print out each string in the vec:

/// Print out each string in a list of strings
#[pyfunction]
fn print_strings(strings: Vec<String>) {
    for s in strings {
        println!("{}", s);
    }
}

If I now run this in the python interpreter with a string that is not a list each character is printed out seperately:

>>> from my_module import print_strings
>>> print_strings("string")
s
t
r
i
n
g

Is there any simple way to ensure single str are treated as [str] using pyo3? Even an Error would be acceptable, as long as users don't pass a string and have it iterate over characters without them noticing.

jeertmans added a commit to jeertmans/pyo3 that referenced this issue Jul 7, 2022
As discussed in PyO3#2342, this PR proposes a way to wrap `str` arguments inside a vector to avoid iterating through chars when it is not desired.
jeertmans added a commit to jeertmans/pyo3 that referenced this issue Jul 13, 2022
Closes PyO3#2342


Refactor to only raise an error based on `isinstance`
@jeertmans
Copy link
Contributor

Hi! Shouldn’t this be closed as #2500 was merged?

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

Successfully merging a pull request may close this issue.

3 participants