• Python3 - TypeError: encoding without a string argument

    I thought I'd document this as although the cause/fix is fairly simple, searching for the error string encoding without a string argument gives a lot of hits for a similarly structured but different error - string argument without an encoding.

    An example backtrace might be:

    Traceback (most recent call last):
      File "./profiler.py", line 346, in 
        meta['config_files']['pdns'] = zip_and_compress(read_file_content('/etc/powerdns/pdns.conf'))
      File "./profiler.py", line 289, in zip_and_compress
        gz = gzip.compress(bytes(s,"utf-8"))
    TypeError: encoding without a string argument
    

    With the example code being fairly simple

    def read_file_content(path):
        ''' Read the entirety of a file into a variable
        '''
        file_content = None
        with open(path, 'rb') as content_file:
            file_content = content_file.read()
    
        return file_content
    
    def zip_and_compress(s):
        ''' Config files can get quite sizeable. To keep the size of our output DB down
        we gzip and then ascii armour them
        '''
        gz = gzip.compress(bytes(s,"utf-8"))
        return base64.b64encode(gz).decode("utf-8")
    
    
    zip_and_compress(read_file_content('/etc/powerdns/pdns.conf'))