qwr
qwr

Reputation: 10891

Python 3 set default bytes encoding

In Python 3, bytes requires an encoding:

bytes(s, encoding="utf-8")

Is there a way to set a default encoding, so bytes always encodes in UTF-8?

The simplest way I imagine is

def bytes_utf8(s):
    return bytes(s, encoding="utf-8") 

Upvotes: 6

Views: 5649

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308101

The documentation for bytes redirects you to the documentation for bytearray, which says in part:

The optional source parameter can be used to initialize the array in a few different ways:

  • If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().

It looks like there's no way to provide a default.

You can use the encode method, which does have a default, given by sys.getdefaultencoding(). If you need to change the default, check out this question but be aware that the capability to do it easily was removed for good reason.

import sys
print(sys.getdefaultencoding())
s.encode()

Upvotes: 7

Related Questions