Python Antipatterns
Posted: Wed Jul 09, 2014 9:55 am
http://lignos.org/py_antipatterns/
This may be useful to some of you who have an interest in learning Python, are new to Python, or haven't touched Python in a while.
Their list comprehension pattern reminded me of some short code I wrote to generate random words in 3 word combos:
Obviously, this example only works on a Unix-like platform with a dictionary file installed. But you get the idea.
I always forget how powerful list comprehensions are (and how useful). If you're writing Python, it's important to pay attention to the features outlined in Antipatterns (above); they'll save you time, they'll make the code more readable, and in some cases more performant.
This may be useful to some of you who have an interest in learning Python, are new to Python, or haven't touched Python in a while.
Their list comprehension pattern reminded me of some short code I wrote to generate random words in 3 word combos:
- Code: Select all
import random
words = [word.strip() for word in open("/usr/share/dict/words").readlines() if len(word) > 4 and word.find("'") < 0]
def randomwords(numwords):
buf = []
for i in range(0, numwords):
buf.append(words[random.randint(0,len(words)-1)])
return " ".join(buf)
randomwords(3)
# Outputs something like 'refutable mollified madame'
Obviously, this example only works on a Unix-like platform with a dictionary file installed. But you get the idea.
I always forget how powerful list comprehensions are (and how useful). If you're writing Python, it's important to pay attention to the features outlined in Antipatterns (above); they'll save you time, they'll make the code more readable, and in some cases more performant.