Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way to know the length of a bytearray variable in python?

Tags:

python

I have this code:

variable = "FFFF"
message = bytearray( variable.decode("hex") )

after this, I want to perform something like this:

message.len()

but it seems that bytearray does not have something like "len()" implemented, is it possible to know the lenght?

like image 848
Javier Ochoa Avatar asked Dec 14 '22 15:12

Javier Ochoa


1 Answers

The idiom used for this in python is len(obj), not obj.len()

>>> v = 'ffff'
>>> msg = bytearray(v.decode('hex'))
>>> len(msg)
2

If you are creating your own class that should be able to report its length, implement the magic method __len__(self), which will be called when the built-in function len() is called and passed an instance of your class.

Why?

See this old post from Guido:

(a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into xa + xb to the clumsiness of doing the same thing using a raw OO notation.

(b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len().

like image 87
bgporter Avatar answered Apr 09 '23 06:04

bgporter