Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Providing Write-Only Attributes

00:00 Providing Write-Only Attributes. You can also create write-only attributes by tweaking how you implement the getter method of your properties. For example, you can make your getter method raise an exception every time you accesses the underlying attribute value.

00:20 On-screen, you’ll see an example of handling passwords with a write-only property.

00:32 The initializer of User takes a username and a password as arguments and stores them in .name and .password, respectively.

00:43 You use a property to manage how your class processes the input password. The getter method raises an AttributeError whenever a user tries to retrieve the current password.

00:53 This turns .password into a write-only attribute. In the setter method of .password, you use os.urandom() to generate a 32-byte random string as your hashing function’s salt. To generate the hashed password, you use hashlib.pbkdf2_hmac().

01:15 Then you store the resulting hashed password in the non-public attribute ._hashed_password. Doing so ensures that you never save the plaintext password in any retrievable attribute.

01:28 Let’s take a look at the write-only attribute in action.

01:36 In this example, you create john as a User instance with an initial password. The setter method hashes the password and stores it in ._hashed_password.

01:52 Note that when you try to access .password directly, you get an AttributeError. Finally, assigning a new value to .password triggers the setter method and creates a new hashed password.

02:12 In the next section of the course, you’ll see some examples of property() in action with some practical examples of how to use it.

Become a Member to join the conversation.