5 ms·
Declarative vs. imperative style in Python
- d0m 17y agoI'm not sure what the article is trying to prove.. The imperative version is short and clean while the functional one is so much more hard to read. However, does it mean that functional style is bad? Some of those functional snippets could have been highly simplified.
- akkartik 17y agoSimplified how?
- deleted 17y ago[deleted]
- d0m 17y agoI also think using declarative isn't judicious for these exemples.
- mkramlich 17y agoI don't think the declarative examples are examples of declarative style. They are both a mix of imperative and functional, with the 'declarative' examples having inner functions.
- deno 17y agoNow I don't like neither example. The second one isn't declarative. Python actually has preferred, declarative way to write this kind of code — just use generators. How much more clearer is this code: def some_func(someList): for elem in someList: # do something with elem yield elem
- endtime 17y agoIsn't the "generative" approach a bit more limited? It works if all you want to do is iterate through the result once, but if you want to do anything more than that with it you'll need a list. No?
- deno 17y agoIt depends on the situation, I guess. You can “cache” specific results inside generator object/function and still return generator. If your result is something one can iterate over you should return generator. If you then need list you can just convert your generator into one. If your list is actually some kind of data structure than perhaps a more object-oriented approach is suitable? Python is not functional language after all. But if all you need is to iterate more than once over generator you can just cache it as a list and reuse if needed.
- dustingetz 17y agoi think the right hand style (whatever it is) is more self-documenting.
- JeanPierre 17y agoWouldn't it be more intuitive to do the following in example 2? def post_process(data): newdict = data.copy() Str = 'df_use_percent' if Str in newdict: newdict[Str] = newdict[Str].rstrip('%') return newdict
- andrewcooke 17y agoyes. (also, newdict = dict(data) seems more natural to me since the same idiom can be used for copying lists, which don't have a copy method).
- jrockway 17y agoPython is unreadable.