-
Notifications
You must be signed in to change notification settings - Fork 108
Python private attributes
-
Affected Components : builtin
-
Operating System : Linux
-
Python Versions : 2.6.x, 2.7.x, 3.1.x, 3.2.x
-
Reproducible : Yes
class Test(object):
def __init__(self):
self.__private = "PRIVATE"
def test(self):
print(self.__private)
print(hasattr(self, "__private"))
print(getattr(self, "__private"))
t = Test()
t.test()
To reproduce the problem copy the source code
in a file and execute the script using the following command syntax:
$ python -OOBRtt test.py
Alternatively you can open python in interactive mode:
$ python -OOBRtt <press enter>
Then copy the lines of code into the interpreter.
In python is possible to assign values private variables but for an inconsistency on the logic, seems not possible to get the value of the same variable.
In the test code we tested this conditions by assigning the value 'PRIVATE'
to a private function:
self.__private = "PRIVATE"
Then the code proceeds by loading the value:
t = Test()
Then as a test we tried to make three operations.
print(self.__private)
PRIVATE
This test proves that the attribute has been set as it's values has been printed.
print(hasattr(self, "__private"))
False
Even if we have been able to print the value of the attribute, a check for the existence of he attribute FAILS and python reports that attribute has not been set.
print(getattr(self, "__private"))
Traceback (most recent call last):
File "test.py", line 15, in <module>
t.test()
File "test.py", line 11, in test
print(getattr(self, "__private"))
AttributeError: 'Test' object has no attribute '__private'
And if we try to get the value of the attribute that has just been set we get an unexpected error from the interpreter as stating that the object does not have an attribute set.
If the language allows for a private attribute (double underscore) to be assigned, should be possible to check if exists using hasattr
* , and should also be possible to get he attribute value using getattr
, but the latter generates an error or Traceback
.
In python name mangling happens only at code compilation time indicating that the problem lies in the code functions of the interpreter as the logic is inconsistent.
We are not aware on any easy solution other than trying to avoid checking private variables in cases like the one examined.
[Python Classes][01] [01]:https://docs.python.org/2/tutorial/classes.html
[Python Functions][02] [02]:https://docs.python.org/2/library/functions.html
[Python bug 8264][03] [03]:http://bugs.python.org/issue8264
Main site: pythonsecurity.org
OWASP Page: owasp.org/index.php/OWASP_Python_Security_Project