On 04/02/2015 02:07 PM, Steven D'Aprano wrote:
<SNIP>
What are the best practices to create more Functional Python?

Best practices:

* Don't force your code to use one style exclusively. Use the most
   natural style for the task. Python makes it easy to mix functional,
   procedural, imperative and object oriented code in the one
   application. Use whatever is most natural for your task.
Good point, but still trying to understand how this is best determined beyond trial and error, and to make sure that my assumptions are correct about this decision.

* Where possible, write your functions and methods in a functional
   style. That means:

- Avoid global variables.
I have got this down.

- Avoid side-effects where possible.
Now getting better at this.

- Separate the logic of your algorithm from the display of results (e.g.
   don't have a method that calculates a result AND prints it; have the
   method calculate the result, and then have the caller print it).
Need to always do this and do it first rather than during re-factoring.

<SNIP>

- Many uses of map() and filter() are better written as generator
   expressions; e.g. instead of:
I now understand generators and I am now using them whenever I see the opportunity.

      filter(lambda s: s.lower().startswith("a"), map(str, mylist))

   you can use:

      (str(x) for x in mylist if s.lower().startswith("a"))


- Where useful, write your code to take advantage of "pipelining"
   style, e.g. using lazy iterators rather than lists. You can then chain
   iterators together to get the desired result.
Yes I have started to do this since seeing the power of pipe-lining.
<SNIP>
What do you mean? Can you show an example?
I added an example in the reply to Alan.
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to