Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python syntax inconsistency?

Tags:

python

I've been reading up on python's special class methods in Dive into Python, and it seems like some methods have odd or inconsistent syntax.

To get the items from a dictionary you would call the dictionary class method items()

>>> my_dictionary.items()
[('name', 'Old Gregg'), ('Race', 'Scaly Man-Fish')]

However, to determine the number of keys in that dictionary you would call len() and supply it with the dictionary as an argument.

>>> len(my_dictionary)
2

I always assumed that methods like len() weren't actually part of whatever class you called them on given their syntax but after reading chapter 5 of Dive into Python I see that len() actually does result in a dictionary method being called.

my_dictionary.__len__()

So why isn't it and methods like it called like a typical class method?

my_dictionary.len()

Is there a convention I'm unaware of?

like image 889
Chris Cummings Avatar asked May 05 '11 04:05

Chris Cummings


2 Answers

Guido van Rossum explained it thusly:

(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(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method.

like image 78
gsteff Avatar answered Sep 20 '22 19:09

gsteff


We are not in the Java world.

There are a lot of methods in Python that are applicable to object if they implement the related API

len() --> __len__()
str() --> __str__()
repr() --> __repr__()

Apart from that:

Why should

my_dictionary.len()

be a method?

In Javascript objects expose their size through the 'length' attribute which is more natural than using a method....sorry, but not all nonsense coming from the Java world is good and must be available in other languages.

like image 23
Andreas Jung Avatar answered Sep 18 '22 19:09

Andreas Jung