4 ms·
It's not designed to be useful, it just is. Functions are objects, yes, and the def statement brings them into being and assigns them to the given name in the c
by jsprinkles 14y ago
It's not designed to be useful, it just is. Functions are objects, yes, and the def statement brings them into being and assigns them to the given name in the current scope:
>>> def f(x):
... return x + 5
>>> type(f)
<type 'function'>
>>> dis.dis(f.func_code)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (5)
6 BINARY_ADD
7 RETURN_VALUE
>>> g = f
>>> g(10)
15
>>> g is f
True
They're just variables in the current scope. If you're quite clever, your brain is already figuring out that has some interesting implications that some libraries use:
>>> import socket
>>> socket.gethostbyname('www.google.com')
'74.125.71.103'
>>> socket.gethostbyname = lambda i: '10.0.0.1'
>>> socket.gethostbyname('www.google.com')
'10.0.0.1'
I will not pass judgement on monkey patching like this, just pointing out it's doable. I know for a fact Ruby can as well.
Functions just being variables has useful properties when you're doing something like fancy switch/case type things (the readability of this is questionable, but it's cool to look at it, like a Duff's device):
>>> i = 1
>>> { str: func1, unicode: func2, int: func3 }.get(type(i), func1)(i)
in func3
Also consider something like this, which is how decorators work (and they're incredibly useful), sort of like a closure:
>>> def maker(i):
... def ret(x):
... return x + i
... return ret
>>> f, g = maker(10), maker(100)
>>> f(5), g(10)
(15, 110)
I'd be surprised if Ruby couldn't do everything I just did.
- mattmanser 14y agoIt's not designed to be useful By useful he means mucking up your program in totally unexpected ways. He's being nice about it being a silly decision to have it behave that way. The entire post reads more like a list of unexpected things that will bite you in the ass.
- adi92 14y agoThanking you for showing me the 'dis' module. Dis is going to be fun to play with!!