It is currently Sat Dec 21, 2024 7:11 pm

Python Antipatterns

If you have something technology-related to share and don't feel like cluttering up General Chat, post it here. Anything is fair game and anything highly technical is preferred.

Python Antipatterns

Postby Zancarius » 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:

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.
I gave that lich a phylactery shard. Liches love phylactery shards.
User avatar
Zancarius
Site Admin
 
Posts: 3907
Joined: Wed Jul 05, 2006 3:06 pm
Location: New Mexico
Gender: Male

Return to Technology Lounge

Who is online

Users browsing this forum: No registered users and 3 guests