4 ms·
For someone who knows zero about D, but is a total Pythonista, how would you compare the meta-programming facilities?
by dbcurtis 10y ago
For someone who knows zero about D, but is a total Pythonista, how would you compare the meta-programming facilities?
- jordigh 10y agoI guess the best comparison to Python would be the dunder methods. You know how in Python a class really is just a dict, right? Like, foo.bar is pretty much syntactic sugar for foo.__get_attribute__(foo.__dict__['bar']) in most cases. Or how a + b is sugar for a.__plus__(b). Well, imagine that all of the things you can do in Python by messing with dunder methods, function decorators, or metaclasses could be precomputed by a compiler and would not even execute at all during runtime. It makes everything really fast at runtime and easy to precompute at compile time.
- dbcurtis 10y agoWell, overriding dunder methods isn't really metaprogramming. It's just method inheritance/override. Is there anything in D similar to decorators? How does the registration pattern work in D, for instance?
- gmfawcett 10y agoDo you mean like this kind of registration decorator? https://github.com/rejectedsoftware/vibe.d/blob/master/examples/rest/source/app.d#L232 https://github.com/rejectedsoftware/vibe.d/blob/master/examp... Decorators (in D, 'user defined attributes', or UDA) work differently. It's not a function-composition feature, but more of a tagging feature. You write a class, function, etc., tag it with custom attributes; and then have a separate compile-time function walk over your code, find the decorators, and augment the code based the meaning of the tags. (I used to wish that D had adopted Python-style decorators, since they are easy to reason about and implement, but I can see the logic of the more general UDA system that they adopted.) In practice, though, you would often use templates to achieve the same effect. Given a memoize template (really, just a memoize function), and an expensive-computation function, auto fastComputer = memoize!expensiveComputer; produces roughly the equivalent of @memoize def expensiveComputer(): ... but with opportunities for compile-time optimization.
- gmfawcett 10y agoYes, and plus you get type safety with all of that! When I'm writing in D, my editor marks all the type errors (and typos) in my code, almost as fast as I make them. The DMD compiler is so quick that there's almost no lag. This leads not only to a rapid development cycle, but a much higher level of reassurance (than I've had when writing, e.g., metaclass hacks in Python).