
Declarative vs. imperative style in Python - twampss
http://www.saltycrane.com/blog/2010/02/declarative-vs-imperative-style-python/
======
deno
Now 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
Isn'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
It 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.

------
d0m
I'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
Simplified how?

------
JeanPierre
Wouldn'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
yes.

(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).

------
mkramlich
I 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.

------
d0m
I also think using declarative isn't judicious for these exemples.

------
dustingetz
i think the right hand style (whatever it is) is more self-documenting.

------
jrockway
Python is unreadable.

