Ray Ray - 3 months ago 6
Python Question

TypeError: 'bytes' object is not callable

Edit:



I made the very trivial mistake of having bound
bytes
to something else previous to executing the following code. This question is now entirely trivial and probably doesn't help anyone. Sorry.

Original question:



Code:

import sys
print(sys.version)
b = bytes([10, 20, 30, 40])
print(b)


Output:

3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-38-21fec5626bc3> in <module>()
1 import sys
2 print(sys.version)
----> 3 b = bytes([10, 20, 30, 40])
4 print(b)

TypeError: 'bytes' object is not callable


Documentation:

Type: bytes
String form: b'hello world'
Length: 11
Docstring:
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object

Construct an immutable array of bytes from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- any object implementing the buffer API.
- an integer


What am I doing wrong?

Answer

You have assigned a bytes value to the name bytes:

>>> bytes([10, 20, 30, 40])
b'\n\x14\x1e('
>>> bytes = bytes([10, 20, 30, 40])
>>> bytes([10, 20, 30, 40])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object is not callable

bytes is now bound to the value b'\n\x14\x1e(', which is not callable. This global is shadowing the built-in. Delete it:

del bytes

to reveal the built-in again.