Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

How do you apply two methods to a function in Python?

I am running this code to create a SHA1 Hash.

import hashlib
import os

"""
   Program to Hash a file, works in Python 2
"""

def sha1sum(filename):
    hash = hashlib.sha1(filename.read())
    return hash.hexdigest()

with open('f1.py') as filename:
    mysum = sha1sum(filename)

print(mysum)

This works in Python 2 but in Python 3 I need to "encode" the data and get the following error message

TypeError: Unicode-objects must be encoded before hashing

A little Googling tells me I need to .encode. Something like this

filename.encoding('utf-8')


From what I can tell this means I need to apply two methods to filename argument

filename.read() and filename.encode('utf-8')

Is this assumption correct?


If so I tried changing

hash = hashlib.sha1(filename.read())

To

hash = hashlib.sha1(filename.read())filename.encode('utf-8')))

And I get the following error

hash = hashlib.sha1(filename.read())filename.encode('utf-8') ^ SyntaxError: invalid syntax


I am not sure what the proper syntax would be or how to proceed. Thanks in advance.

2 Answers

Steven Parker
Steven Parker
243,318 Points

I'm not familiar with these particular functions, but usually methods can be chained by joining them with a period (.), assuming the method returns an object of the same type it was applied to. So you probably want something like: filename.read().encoding('utf-8'). And the whole thing would likely be:

hash = hashlib.sha1(filename.read().encoding('utf-8'))

(Is it encode or encoding?)

This worked! Fantastics. Thanks!