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

getattr() should work whenever hasattr() is True #5224

Closed
mboes opened this issue May 20, 2018 · 2 comments
Closed

getattr() should work whenever hasattr() is True #5224

mboes opened this issue May 20, 2018 · 2 comments
Assignees
Labels
P2 We'll consider working on this in future. (Assignee optional) type: bug

Comments

@mboes
Copy link
Contributor

mboes commented May 20, 2018

Description of the problem

hasattr() returns True even when for the given attribute getattr() always throws an exception. This has the unfortunate side effect that one cannot safely getattr() the value of an attribute, even when guarding it with hasattr() beforehand.

I would expect the following intuitive property to hold:

getattr(x, "foo") returns a value (does not raise an exception) if and only if hasattr(x, "foo") == True.

But since at least e5e3e91, this
does not hold.

Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.

x = struct(a = 1)
print(dir(x))
for f in dir(x):
  if hasattr(x, "a"):
    print(getattr(x, "a", "method"))

raises an exception because hasattr(x, "to_json") is True but getattr(x, "to_json") doesn't work, even when a default value ("method") is provided.

What's the output of bazel info release?

v0.13.0

Have you found anything relevant by searching the web?

Nothing in GitHub issues.

@katre katre added type: bug P2 We'll consider working on this in future. (Assignee optional) category: extensibility > skylark labels May 23, 2018
@fweikert fweikert removed their assignment Nov 19, 2018
@laurentlb
Copy link
Contributor

@c-parsons, with your recent changes related to method calls, this might be easier to do.

bazel-io pushed a commit that referenced this issue Jul 24, 2019
…sing getattr

Related: bazelbuild/starlark#20 (comment), #5224

It's now possible to call methods in two steps `y = x.f; y()`
Also, `getattr` can now be used to retrieve built-in methods.

Closes #8931.

PiperOrigin-RevId: 259711316
@brandjon
Copy link
Member

From inspection of the code, it looks like this is fixed by Alan's refactoring. hasattr checks for both annotated methods/fields and Structure fields. And getattr has supported accessing builtin methods for quite a while now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
P2 We'll consider working on this in future. (Assignee optional) type: bug
Projects
None yet
Development

No branches or pull requests

6 participants