Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map object has no len() in Python 3

I have this Python tool written by someone else to flash a certain microcontroller, but he has written this tool for Python 2.6 and I am using Python 3.3.

So, most of it I got ported, but this line is making problems:

data = map(lambda c: ord(c), file(args[0], 'rb').read())  

The file function does not exist in Python 3 and has to be replaced with open. But then, a function which gets data as an argument causes an exception:

TypeError: object of type 'map' has no len() 

But what I see so far in the documentation is, that map has to join iterable types to one big iterable, am I missing something?

What do I have to do to port this to Python 3?

like image 249
user3219624 Avatar asked Feb 05 '14 09:02

user3219624


People also ask

Does Python have no Len?

The Python "TypeError: object of type 'function' has no len()" occurs when we pass a function without calling it to the len() function. To solve the error, make sure to call the function and pass the result to the len() function.

What is map () in Python?

Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.

Is there a map object in Python?

Python map() function is used to apply a function on all the elements of specified iterable and return map object. Python map object is an iterator, so we can iterate over its elements. We can also convert map object to sequence objects such as list, tuple etc. using their factory functions.

How do I find the size of a map in Python?

int n = mymap. size(); Doc.


1 Answers

In Python 3, map returns an iterator. If your function expects a list, the iterator has to be explicitly converted, like this:

data = list(map(...)) 

And we can do it simply, like this

with open(args[0], "rb") as input_file:     data = list(input_file.read()) 

rb refers to read in binary mode. So, it actually returns the bytes. So, we just have to convert them to a list.

Quoting from the open's docs,

Python distinguishes between binary and text I/O. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding.

like image 170
thefourtheye Avatar answered Sep 20 '22 16:09

thefourtheye