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
[doc] hasattr doesn't show private (double underscore) attributes exist #52511
Comments
I just spend a while tracking down a bug in my code which turned out to be an unexpected behaviour of hasattr. Running this class Test(object):
def __init__(self):
self.__private = "Hello"
def test(self):
print(self.__private)
print(hasattr(self, "__private"))
print(getattr(self, "__private"))
t = Test()
t.test() Prints >>> t.test()
Hello
False
Traceback (most recent call last):
File "private_test.py", line 10, in <module>
t.test()
File "private_test.py", line 7, in test
print(getattr(self, "__private"))
AttributeError: 'Test' object has no attribute '__private'
>>> Indicating that even though we just printed self.__private hasattr() can't find it nor getattr(). I think this is probably the intended behaviour, but it does seem inconsistent. Probably all that is required is a documentation patch... Maybe something add something like this to the end of http://docs.python.org/library/functions.html#hasattr Note that hasattr won't find private (double underscore) attributes unless the mangled name is used. |
You are correct, this is the expected behavior. Name mangling happens only at compilation time (see http://docs.python.org/reference/expressions.html#atom-identifiers). A doc note for get/setattr would probably be useful. (I removed 3.3; that version doesn't exist yet and should only be set on issues that can only be dealt with in 3.3, such as removing something deprecated in 3.2.) |
Attached a patch that adds a note for getattr and setattr. hasattr is documented in terms of getattr so I would say it's not needed there. I don't know if the interaction with private attributes is confusing enough that it's worth increasing the verbosity of the getattr and setattr docs, all in all I think I'm +0 to adding the note and -0 to just closing the bug as by design and no doc change needed. |
Thanks for merging this Ethan! I think we can close this now (unless you want me to backport this to 3.9 and 3.8 as well). |
All the PRs have landed in bugfix branches so I'm closing this issue. Thanks Irit and Ethan! |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: