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

New linter for utils::hasName() #2650

Open
m-muecke opened this issue Aug 29, 2024 · 3 comments
Open

New linter for utils::hasName() #2650

m-muecke opened this issue Aug 29, 2024 · 3 comments

Comments

@m-muecke
Copy link

m-muecke commented Aug 29, 2024

Since R 3.4.0 utils::hasName() was added as a convient way of testing the existence of a name i.e. the pattern "name" %in% names(x) or for checking the !is.null(x$abc) pattern without partial matching (taken from the docs):

 x <- list(abc = 1, def = 2)
 !is.null(x$abc) # correct
 !is.null(x$a)   # this is the wrong test!
 hasName(x, "abc")
 hasName(x, "a")

There is also the basically equivalent rlang::has_name() as a common pattern.

@AshesITR
Copy link
Collaborator

Note that $ can be overridden. reticulate does this for example. "a" %in% names(x) is probably fine to lint.

@m-muecke
Copy link
Author

m-muecke commented Aug 29, 2024

Note that $ can be overridden. reticulate does this for example. "a" %in% names(x) is probably fine to lint.

As well as active bindings in R6. The name checking seems to be the only relevant case.

@MichaelChirico
Copy link
Collaborator

I'm slightly ambivalent on whether hasName(x, nm) is better than nm %in% names(x), seem similar. Happy to host the linter though, it seems reasonable enough as a case of "use the specific function from base".

Since %in% is just match() under the hood, we can also detect the direct match() equivalent, which is much worse:

match(nm, names(x), 0L) > 0L

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

No branches or pull requests

4 participants