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

attr_getter() uses partial matching, which is error-prone/dangerous #460

Closed
huftis opened this issue Feb 6, 2018 · 3 comments · Fixed by #461
Closed

attr_getter() uses partial matching, which is error-prone/dangerous #460

huftis opened this issue Feb 6, 2018 · 3 comments · Fixed by #461
Labels
bug an unexpected problem or unintended behavior wip work in progress

Comments

@huftis
Copy link
Contributor

huftis commented Feb 6, 2018

Here’s a bug/misfeature is was bitten by today. Basically, I was trying to extract the label associated with each variable in a tibble, using (bascially) map(df, attr_getter("label")).

However, for some of the variables, the value of the labels (note the s) attribute, a ‘> 1’-length vector, were extracted instead. It turned out that this happens when the label attribute is missing. The reason is partial matching on the attribute name, which unfortunately is the default in attr().

It’s to late to change the base attr() function, but partial matching is dangerous ☠️, and I see no reason that this should be the default in attr_getter() too!

To fix this, one only needs to add exact = TRUE in the call to the attr function in get_attr().

Reprex:

library(purrr)
x = c(0, 1, 1, 0)
attr(x, "labels") = c(`0` = "Female", `1` = "Male")
get_label = attr_getter("label")
get_label(x) # Expected output: NULL
#>        0        1 
#> "Female"   "Male"
@hadley
Copy link
Member

hadley commented Feb 7, 2018

Do you want to do a PR?

@hadley hadley added the bug an unexpected problem or unintended behavior label Feb 7, 2018
@huftis
Copy link
Contributor Author

huftis commented Feb 7, 2018

Sure, @hadley, I can try to create a PR.

@hadley hadley added the wip work in progress label Feb 7, 2018
huftis added a commit to huftis/purrr that referenced this issue Feb 7, 2018
Changed the `attr_getter()` fuction to no longer uses partial matching.
For example, if an `x` object has a `labels` attribute but no `label`
attribute, `attr_getter("label")(x)` will no longer extract the `labels`
attribute (fixes tidyverse#460).

Also added some documentation on the `attr_getter()` function.
@huftis
Copy link
Contributor Author

huftis commented Feb 7, 2018

I’ve now added a PR for this issue, @hadley.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug an unexpected problem or unintended behavior wip work in progress
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants