Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can the __bytes__ method be found?

The official documentation says:

object.__bytes__(self)

Called by bytes to compute a byte-string representation of an object. This should return a bytes object.

But when I do dir(object) or dir(bytes) or dir(bytearray), the __bytes__ method does not show up. So where can it be found?

like image 314
debashish Avatar asked Aug 05 '17 13:08

debashish


People also ask

What does bytes () do in Python?

Python bytes() Function The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size.

How do you split bytes in Python?

Solution: To split a byte string into a list of lines—each line being a byte string itself—use the Bytes. split(delimiter) method and use the Bytes newline character b'\n' as a delimiter.


1 Answers

PEP 428's pathlib (since Python 3.4) may be the most common use of bytes.

The string representation of a path is the raw filesystem path itself (in native form, e.g. with backslashes under Windows), which you can pass to any function taking a file path as a string:

>>>
>>> p = PurePath('/etc')
>>> str(p)
'/etc'

Similarly, calling bytes on a path gives the raw filesystem path as a bytes object, as encoded by os.fsencode():

>>>
>>> bytes(p)
b'/etc'

These conversions happen through pathlib.__str__() and pathlib.__bytes__() magic methods.

like image 56
ephemient Avatar answered Oct 23 '22 17:10

ephemient