320 points · by aburan28 · 12y ago · 237 comments
- Bare except: statements (that catches everything, even Ctrl-C)
- Mutables as default function/method arguments
- Wildcard imports!
Given a function like:
def append_one(l=[]):
l.append(1)
return l
What does this return each time? >>> append_one()
>>> append_one()
>>> append_one()Still, I'd change this to something like:
def append_five(l=[]):
l.append(5)
return l
It tests the same thing (knowledge of how default parameters work), but without the confounding problem of similar-looking characters. Of course, syntax highlighting would help the applicant out.All of that being said, I still don't doubt that many developers don't know what they should about default parameters.
because the behavior is the same, whether or not they misread an 'l' as a 1.
In my experence your much better off with people that look at odd syntax and say, "I don't know what that does" vs those who do.
Using the default value in some capacity isn't that uncommon... Though maybe you were speaking to a more general case? for example, decoding a an obfuscated C file.
I know python is not unique in having warts like this, but it's pretty b.s. in general that unexpected behavior is just thought to be okay, especially in a language meant to be very accessible, and most especially since it's being used as a perfectly valid metric for disqualifying new python programmers from employment.
If the industry as a whole cared about evidence-based, non-superstitious, non-monoculture-reinforcing hiring practices, we'd realize that tripping people up and judging programming capability based on minutia is as unfair as it is self-defeating.
It is simply a easy way to gauge a candidate's proficiency with the language. It also helps if they know that this is a problem. You'd be shocked to know a lot of people on the market for jobs writing python don't get this question correct, but the smart ones often do when talking through it even if they didn't originally.
a_list_of_words = "my list of words".split(" ")
I never enquired why, since there were bigger issues in the code e.g. "unit testing" by running the code, taking the result and putting it as the check value. By running repr(value), copying out the string then comparing self.assertEqual(repr(value), '[<Object1: unicode_value>, ...]')
df_subset = df['date buyer nwidgets'.split()]
That is far easier to type than the explicit list, with all its punctuation. Now, it's definitely weird that they did a `split(" ")` rather than just using the default, but the idea is the same.I do try to strip stuff like that out before I put it into a script, replacing it with the explicit list, but I'm never sure if that actually improves anything. It's not as if the explicit list is any easier to read.
In [1]: "a string r".split(" ")
Out[1]: ['a', '', '', '', 'string', '', '', '', '', 'r']
In [2]: "a string r".split()
Out[2]: ['a', 'string', 'r'](That sentence I wrote about using hashable types need not apply, sorry!)
If you ran that code, you would get this error:
TypeError: list indices must be integers, not listInefficent, or bizarre way to do it maybe.
Anti-pattern is supposed to mean something more, though.
In this case there are no adverse effects and no ambiguity -- so, I guess the programmer was just lazy to construct the list.
@a_list_of_words = qw/my list of words/;
there
a_list_of_words = %w{my list of words} >>> qw = str.split
>>> qw('my list of words')
['my', 'list', 'of', 'words']a_tuple_of_words = ("my", "tuple", "of", "words")
or
a_tuple_of_words = "my", "tuple", "of", "words"
But yes, Python misses entirely the point of tuples, treating them as read-only lists.
http://dozzie.jogger.pl/2014/04/11/python-tuples-the-useless...
It would really make sense to change the semantics of Python to fix this issue.
There are other dynamic languages with functions as first class objects which don't share the "mutable default arguments" gotcha.
But having said that, any change regarding this would break backward compatibility.
def foo(default_arg = []):
Why can't that just be shorthand for: def foo(default_arg = ParamNone):
if default_arg == ParamNone:
default_arg = []
How would that break first class functions?Example: nose.tools
For example, this is a real method in one of my projects:
def listen(self, address, ssl=False, ssl_args={}):
pass
I like the way this turns up in the docs because it's immediately clear that ssl_args needs to be a dict. Otherwise I have to describe it in words.Why not just add @param annotations in your docstrings instead?
If they need to touch this argument in an overridden method and they don't know what they are doing, then yes.
> Why not just add @param annotations in your docstrings instead?
I'm using Sphinx and it renders them separately. I want the empty dict to show up in the function signature.
It's very common for libraries to make values evaluate to False, and very easy to get bugs if you just lazily test with 'if x'.
Sqlalchemy springs to mind immediately as one of the common ones where using any() and if x: is a reeeeeallly bad idea; there are plenty of others.
I'm pretty skpetical about modifying your coding behavior based on what libraries you happen to be currently using.
'If x' isn't your friend.
(bool(datetime.time(0)), bool(datetime.time(1))) == (False, True)
I always consider `if x:` a bug, unless x can only be a boolean. Furthermore, it seriously hinders readability and clarity of the code.I got bit by this once, and it's certainly... strange (it's also surprising). It's considered "behavior consistent with the rest of Python" [1] (which I can agree with) even if it makes little sense in terms of immediate readability to someone who hasn't previously encountered it. Fortunately, the workaround is easy, and it is documented.
There's at least a couple of spats on the mailing list regarding this feature that are of interest to the curious or at least those who are interested in the history of such behavior.
Oh, like this? ;)
var eventA = new Date(), eventB = new Date();
if (!parseInt((eventA - eventB) / 1000)) {
console.log("these events occurred simultaneously");
} else {
// troll harder with confusing use of 'asynchronous'
console.log("these events occurred asynchronously");
} "Explicit is better than implicit."
If you mean is not None, you should say is not None.It's fast and readable and there are no "just be aware that" disclaimers to tack on afterwards.
If you're checking to see if that value is None, then yes - you should check that.
If you're merely checking if the value is truthy, then using "if x:" is completely legitimate.
Great talk on avoiding some of the common pitfalls new python developers step in. Exposes some nice language features.
https://speakerdeck.com/pyconslides/transforming-code-into-b...
is inside-out or backwards or backwards. I want the nested for being the less specific case:
x = [letter for letter in word for word in words]
makes more sense in my mind.(It's also my first answer to the "what're some warts in the your language of choice).
x = [for word in words: for letter in word: letter]
This also has the advantage of being readable left to right without encountering any unbound identifiers like all other constructs in Python.I know how to use list comprehensions, but often avoid using them and use the standard for loops. List comprehensions look nice and clean for small examples, but they can easily get long and become mentally hard to parse. I would rather go for three 30 character lines instead of one 90 character line.
Personally I think list comprehensions are the most beautiful part of Python, though sometimes I use map() when I'm trying to be explicitly functional (I realize it's allegedly slower, etc).
Generally I think list comprehensions are cleaner and allow you to write purer functions with fewer mutable variables. I disagree that deeply nested for loops are necessarily more readable.
However, I think he was referring to if the conditionals/additional modifications needed to build your list get a bit excessive, so you'd have a like... [dostuffto(A) for A in alsodostuffto(LIST) if conditional(A)] (but with more complex operations at each step).
Granted at that point you can argue that you should do just as my example shows and put the "dostuffto" into more encapsulated functions, but sometimes that doesn't seem like the right choice.
$ python -mtimeit -s'nums=range(10)' 'map(lambda i: i + 3, nums)' 1000000 loops, best of 3: 1.61 usec per loop
$ python -mtimeit -s'nums=range(10)' '[i + 3 for i in nums]' 1000000 loops, best of 3: 0.722 usec per loop
Function calls have overhead in python, list comprehensions are implemented knowing this fact and avoiding it so the heavy lifting ultimately happens in C code.
$ python -mtimeit -s'nums=range(10)' '[str(i) for i in nums]' 100000 loops, best of 3: 2.57 usec per loop
$ python -mtimeit -s'nums=range(10)' 'map(str, nums)' 1000000 loops, best of 3: 1.88 usec per loop
$ python -mtimeit -s'nums=range(10)' 'import math' '[math.sqrt(i) for i in nums]' 100000 loops, best of 3: 3.25 usec per loop
$ python -mtimeit -s'nums=range(10)' 'import math' 'map(math.sqrt, nums)' 100000 loops, best of 3: 2.55 usec per loop
Even though you could construe map as "half as fast" (or twice as slow) as the equivalent comprehension, I don't see a difference of ~1 usec making any difference in my code thus far. Good to know, though.
In a case where you need to do a lot of nested appends, I've found that even a long list comprehension can be easier to read. You just have to be sure to properly indent it and break it up into multiple lines. My rule is that every extra `for` starts a new line, and sometimes moving the predicate to its own line when it's too long, too.
To my eye, the list comprehension version is reasonable. But I like the imperative style better: it uses the most basic language features and at a glance you can tell what it does. My favourite is the dictionary comprehension version, it's the shortest but still conveys clearly what it's doing.
I use dict comprehensions quite frequently in my own code as well.
alist = [foo(word) for word in words]
is considered more Pythonic than map alist = map(foo, words)Compare:
alist = [x**2 for x in mylist if x%3==0]
to alist = map(lambda x: x**2,filter(lambda x: x%3==0, mylist)
Plus python also has set comprehension and dict comprehension, which share essentially the same syntax. alist = (map (**2) . filter (\x -> x `mod` 3 == 0)) myList
Or: alist = (map (**2) . filter ((== 0) . (`mod` 3))) myList
If alist is a transformation, and not applied to myList, it's cleaner: alist = map (**2) . filter ((== 0) . (`mod` 3))
Though Haskell also has list comprehensions, with more "mathy" syntax: alist = [x**2 | x <- mylist, x `mod` 3 == 0] alist = [foo(word) for word in words if word.startswith('a')]
alist = map(foo, filter(lambda word: word.startswith('a'), words))
Which reads better? begins_with_a = lambda x: x.startswith('a')
alist = map(foo, filter(begins_with_a, words)) ;; clojure
(let [begins-with-a #(.startsWith % "a")
foo #(do-some-stuff-with %)]
(-> words (filter begins-with-a) (map foo))))
# ruby
words.filter { |e| e.start_with?(?a) }.map { |e| foo(e) }
It doesn't really make sense for things like `len` and `map` to be global functions in object-oriented languages. alist = words.filter(lambda word: word.startswith('a')
.map(foo)
That being said, my Python is limited and I don't know it filter/map are available as methods of a list. At the end of the day, there are cases where list comprehensions are much cleaner/understandable... and cases where the reverse is true.They're not. Which is a shame in my opinion, because as you've written it you can clearly read the operations in the order they happen, ie. filter followed by map. Instead, you do have to do the second line of what blossoms wrote above.
And I don't think it's possible to write a list comprehension that reads in execution order, either :(
(as it is now, list comprehensions requiring various references to result of a function call evaluate the function each time it's used)
the other reason its considered more idiomatic in Python is just because the compiler does a better job of parsing and optimizing list comprehensions.
Where as map could be anything. It could be redefined for all you'd know.
words = ['w1', 'w2', 'w3']
[word[1] for word in words]
['1', '2', '3']
map(lambda x: x[1], words)
['1', '2', '3']
I like looking at the list comprehension better. The use of lambda looks forced in this case. I also imagine there's a penalty for calling the (anonymous) function in map. map(itemgetter(1), words)You cannot index a map object, for example.
> The simplifications employed (for example, ignoring generators and the power of itertools when talking about iteration) reflect its intended audience.
Are generators really that hard? (Not a rhetorical question!)
The article mentions problems resulting from the creation of a temporary list based on a large initial list. So, why not just replace a list comprehension "[ ... ]" with a generator expression "( ... )"? Result: minimal storage requirements, and no computation of values later than those that are actually used.
And then there is itertools. This package might seem a bit unintuitive to those who have only programmed in "C". But I think the solution to that is to give examples of how itertools can be used to create simple, readable, efficient code.
>>>def isempty(l):
>>> return not bool(l)
>>>isempty([])
True
>>>isempty(None)
True
If embedded within your program logic this kind of pattern can waste precious time with debugging. You can catch your errors much more quickly if you are explicit with your comparisons.I have seen countless instances of people writing the logic to output commas in between items (like for CSV export) that they want to concatenate into a string.
header_line = ','.join( header for header in headers )
csv_line = ','.join( str(dataset[key]) for key in dataset.keys() )
Example for a case of a dictionary mapping a string to a bunch of numbers. ','.join(headers)> If you aren't following it, you should have good reasons beyond "I just don't like the way that looks."
Core dev and Guido have said many times PEP 8 are not holy.
See https://mail.python.org/pipermail/python-dev/2010-November/1...
In essence, a "stupid reason" like "I don't like it" is a valid reason not to adopt PEP 8.
In fact, I don't like the PEP 8 recommendation on docstring. I like Google's docstring (aka napoleon in Sphinx contrib-module).
http://sphinxcontrib-napoleon.readthedocs.org/en/latest/exam...
1. In "Checking for contents in linear time" both examples are the same. Perhaps remove the list entirely in the second example
2. Itertools.islice helps if you need to slice a list with a bajillion elements
lyrics_list = ['her', 'name', 'is', 'rio']
words = make_wordlist() # Pretend this returns many words that we want to test
for word in words:
if word in lyrics_list: # Linear time
print word, "is in the lyrics"
# Do thislyrics_list = ['her', 'name', 'is', 'rio']
lyrics_set = set(lyrics_list) # Linear time set construction
words = make_wordlist() # Pretend this returns many words that we want to test
for word in words:
if word in lyrics_list: # Constant time
print word, "is in the lyrics"
the second example should read ... if word in lyrics_set: ...> First, don't set any values in the outer scope that > aren't IN_ALL_CAPS. Things like parsing arguments are > best delegated to a function named main, so that any > internal variables in that function do not live in the > outer scope.
How do I inspect variables in my main function after I get unexpected results? I always have my main logic live in the outer scope because I often inspect variables "after the fact" in iPython.
How should I be doing this?
There's a big difference between "scripting" and "writing software" in terms of best practices.
If you're writing some ETL scripts in an IPython notebook, it would be overkill to encapsulate everything to keep your global scope clean.
It's very difficult to write automated tests when all logic is in outer scope rather than chunked into functions.
# Do this
lyrics_set = set(lyrics_list) # Linear time set construction
words = make_wordlist()
for word in words:
if word in lyrics_set: # Constant time
print word, "is in the lyrics"
You could do this: lyrics_set = set(lyrics_list)
words = set(make_wordlist())
matched_words = list(lyrics_set & words)
for word in matched_words:
print word, "is in the lyrics" for word in (set(lyrics_list) & set(words)):
print('{} is in the lyrics'.format(word)) print " is in the lyrics \n".join([set(lyrics_list) & set(words)]), "is in the lyrics" >>> lyrics_list = ["her", "name", "is", "rio"]
>>> words = ["is", "rio"]
>>> print '\n'.join("{} is in the lyrics".format(word) for word in set(lyrics_list) & set(words))
rio is in the lyrics
is is in the lyricsDon't ever do this.
print('\n'.join(['{} is in the lyrics'.format(word)) for word in (set(lyrics_list) & set(words))]) matched_words = set(lyrics_list).intersection(make_wordlist())Generally speaking, one should just return from within the loop.
It seems to me that when people say "Python" they still mostly mean Python 2, where range returns a list and xrange a generator. In Python 3 there is no xrange and range returns a generator, but I think people still most often call that language "Python 3", not "Python".
An (anti)pattern is something abstract and can be applied to any other similar language.
Don't ask what's "more Pythonic" or "less Pythonic", Python is not a cult, it's a very practical scripting language. Ask for benefits and weaknesses of a given approach in given circumstances.
But computer languages, unlike human languages, are precise. Their intent is clear. And you'll never encounter a case where the Python 3 interpreter hasn't heard of that particular Python 3 keyword you're using.
It's also not an excuse to avoid certain features of a language, when using them leads to a better and simpler solution, just because they're less popular. Programming is not an exercise in popularity.
On the other hand, human language is fuzzy and full of phrases that consist of statements having nothing to do with their meaning. Such as me saying "your argument doesn't hold water".
Human languages also have additional layers entirely separate from the primary meaning of a conversation, such as sending social cues like "how smart am I", "do I like you", "do I fit in this group", and "am I a leader or a follower". Each layer of concern drives a certain way of expression and imitation, none of which occurs (or should occur) when writing computer code.
A better example to compare to programming code would be mathematical notation. As long as you express your intent shortly, using the available mathematical notation, people will be fine, and your intent will be clear.
I've never seen someone ask in a math forum if their formula is more Mathematic one way, or another way.
https://docs.python.org/2/tutorial/controlflow.html#for-stat...
But the tutorial in the Python docs has pretty high information density and good coverage of things like this.
(I think there is some risk that this comment will be interpreted as If you don't know enumerate you need to look at the tutorial. That isn't what I intend, I just want to point out that the tutorial is a reasonably dense resource that hits on a lot of stuff like enumerate.)
J/K, while this is technically a limitation of Python 2, there actually is izip in itertools package which is a generator and works in similar way to zip in python 3.
Why a function named `main`? We're not writing C here, there's no need for a function named `main`. Let's call it something that's actually useful, like `parse_cmd_arguments`
As such, testing for membership is an O(1) hash table lookup. If you're skeptical:
$ python -m timeit -s 'nums=range(1000000)' '100000 in nums'
1000 loops, best of 3: 1.4 msec per loop
$ python -m timeit -s 'nums=range(1000000)' '500000 in nums'
100 loops, best of 3: 7.15 msec per loop
$ python -m timeit -s 'nums=range(1000000)' '900000 in nums'
100 loops, best of 3: 13 msec per loop
$ python -m timeit -s 'nums=set(range(1000000))' '100000 in nums'
10000000 loops, best of 3: 0.0572 usec per loop
$ python -m timeit -s 'nums=set(range(1000000))' '500000 in nums'
10000000 loops, best of 3: 0.057 usec per loop
$ python -m timeit -s 'nums=set(range(1000000))' '900000 in nums'
10000000 loops, best of 3: 0.0584 usec per loop