I recently came across syntax I never seen before when I learned python nor in most tutorials, the .. notation, it looks something like this:

f = 1..__truediv__ # or 1..__div__ for python 2

print(f(8)) # prints 0.125 

I figured it was exactly the same as (except it's longer, of course):

f = lambda x: (1).__truediv__(x)
print(f(8)) # prints 0.125 or 1//8

But my questions are: How can it do that? What does it actually mean with the two dots? And how can you use it in a more complex statement (if possible)?

This will probably save me many lines of code in the future...:)

share|improve this question
4  
Please don't do this. – Peter Wood 2 hours ago
    
    
Note: (1).__truediv__ is not really the same as 1..__truediv__, as the former calls int.__truediv__ while the latter does float.__truediv__. Alternatively, you can also use 1 .__truediv__ (with a space)` – tobias_k 37 mins ago

What you have is a float literal without the trailing zero, which you then access the __truediv__ method of. Its not an operator in itself, the first dot is part of the float value, the second is the dot operator to access the objects properties and methods.

You can reach the same point by doing the following.

>>> f = 1.
>>> f
1.0
>>> f.__floordiv__
<method-wrapper '__floordiv__' of float object at 0x7f9fb4dc1a20>

Another example

>>> 1..__add__(2.)
3.0

Here we add 1.0 to 2.0, which obviously yields 3.0.

share|improve this answer
19  
So what we found is a dev who sacrificed a lot of clarity for a little brevity and here we are. – TemporalWolf 3 hours ago

Two dots together may be a little awkward at first:

f = 1..__truediv__ # or 1..__div__ for python 2

But it is the same as writing:

f = 1.0.__truediv__ # or 1.0.__div__ for python 2

Because float literals can be written in three forms:

normal_float = 1.0
short_float = 1.  # == 1.0
prefixed_float = .1  # == 0.1
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.