4 ms·
You can sort of do this with type (and this probably makes python purists really angry, but I've done similar once or twice): def make_window(x1, x2):
by tsuraan 12y ago
You can sort of do this with type (and this probably makes python purists really angry, but I've done similar once or twice):
def make_window(x1, x2):
lo, hi = sorted( (x1, x2) )
window = type('Window', (object,), {
'__call__' : lambda _, x: lo <= x <= hi,
'__repr__' : lambda _: '<%s..%s>' % (lo, hi)
})
return window()
That's actually making a new class called 'Window', inheriting from object, with a call and a repr special method. I still haven't personally decided whether it's gross or not, but I am pretty sure it's not pythonic.
- kazagistar 12y agoThe reason that is gross is that you are essentially creating a new class each time you call it, instead of just creating an instance. Plus, if we really wanted to, we could do something insane, like def window_repr(self): return '<%s..%s>' % (self.__closure__[0], self.__closure__[1]) ... but we are trying to program in python. We have standards.
- cgranade 12y agoWith that approach, each call to ``make_window`` produces a distinct type, such that isinstance couldn't be used to compare two windows. That kind of breaks the idea of a "type", I think, as being a collection of values.
- abecedarius 12y agoYeah, it's possible. My bigger point, which I should've made explicit: Python with nested scopes and classes has two ways to make an object. (Originally it had only classes.) A Python-like language with just one way of defining objects, using nested scopes like my "def window:" above, would be simpler and more concise and more Pythonic (in the sense that there's one and only one obvious way to do it). It's obviously too late to call that language Python, which disappoints me. When the obvious way to do it is very different depending on how many methods an object gets (a function for one, a class for more), refactorings like my example get kind of annoying.