What is f = 1..__truediv__
?
f
is a bound special method on a float with a value of one. Specifically,
1.0 / x
in Python 3, invokes:
(1.0).__truediv__(x)
Evidence:
class Float(float):
def __truediv__(self, other):
print('__truediv__ called')
return super(Float, self).__truediv__(other)
and:
>>> one = Float(1)
>>> one/2
__truediv__ called
0.5
If we do:
f = one.__truediv__
We retain a name bound to that bound method
>>> f(2)
__truediv__ called
0.5
>>> f(3)
__truediv__ called
0.3333333333333333
If we were doing that dotted lookup in a tight loop, this could save a little time.
Parsing the Abstract Syntax Tree (AST)
We can see that parsing the AST for the expression tells us that we are getting the __truediv__
attribute on the floating point number, 1.0
:
>>> import ast
>>> ast.dump(ast.parse('1..__truediv__').body[0])
"Expr(value=Attribute(value=Num(n=1.0), attr='__truediv__', ctx=Load()))"
You could get the same resulting function from:
f = float(1).__truediv__
Or
f = (1.0).__truediv__
Deduction
We can also get there by deduction.
Let's build it up.
1 by itself is an int
:
>>> 1
1
>>> type(1)
<type 'int'>
1 with a period after it is a float:
>>> 1.
1.0
>>> type(1.)
<type 'float'>
The next dot by itself would be a SyntaxError, but it begins a dotted lookup on the instance of the float:
>>> 1..__truediv__
<method-wrapper '__truediv__' of float object at 0x0D1C7BF0>
No one else has mentioned this - This is now a "bound method" on the float, 1.0
:
>>> f = 1..__truediv__
>>> f
<method-wrapper '__truediv__' of float object at 0x127F3CD8>
>>> f(2)
0.5
>>> f(3)
0.33333333333333331
We could accomplish the same function much more readably:
>>> def divide_one_by(x):
... return 1.0/x
...
>>> divide_one_by(2)
0.5
>>> divide_one_by(3)
0.33333333333333331
Performance
The downside of the divide_one_by
function is that it requires another Python stack frame, making it somewhat slower than the bound method:
>>> def f_1():
... for x in range(1, 11):
... f(x)
...
>>> def f_2():
... for x in range(1, 11):
... divide_one_by(x)
...
>>> timeit.repeat(f_1)
[2.5495760687176485, 2.5585621018805469, 2.5411816588331888]
>>> timeit.repeat(f_2)
[3.479687248616699, 3.46196088706062, 3.473726342237768]
Of course, if you can just use plain literals, that's even faster:
>>> def f_3():
... for x in range(1, 11):
... 1.0/x
...
>>> timeit.repeat(f_3)
[2.1224895628296281, 2.1219930218637728, 2.1280188256941983]