by tribaal · 12y ago · 0 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.
If the candidate correctly deduces what will happen, I'll ask them to write a bug-free version, which looks like one of the below:
def append_one(var=None):
var = var or []
var.append(1)
return var
def append_one(var=None): if var is None:
var = []
var.append(1)
return var
Mutability is a very subtle but very important concept to understand in python. Everyone who uses python for non-trivial code should know it well: https://docs.python.org/2/reference/datamodel.htmlbecause the behavior is the same, whether or not they misread an 'l' as a 1.
In [1]: a = []
In [2]: a.append(a)
In [3]: a
Out[3]: [[...]]
In [4]: a[0]
Out[4]: [[...]]
In [5]: a[0][0]
Out[5]: [[...]]
In [6]: a[0][0][0]
Out[6]: [[...]]
In [7]: a[0][0][0][0]
Out[7]: [[...]]
In [8]: a.append(a)
In [9]: a
Out[9]: [[...], [...]]
In [10]: a[0][1][0] is a
Out[10]: True
In [11]: id(a)
Out[11]: 4547140064
In [12]: id(a[0][1][0])
Out[12]: 4547140064In 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'] >>> filter(None, " quick hack for split".split(" "))
['quick', 'hack', 'for', 'split'](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...
No, a structure is, you know, a structure -- what C calls a struct. Python calls it a namedtuple. If some people call it just a tuple, well, that's a difference in terminology, but it doesn't mean Python is confused about the concepts, it's just using terminology you're not used to.
Also, if we're going to be pedantic about the meaning of data types, your blog post is wrong about lists. You say "position in the list doesn't matter", but that means ordering doesn't matter, and an unordered collection of similar objects is a set, not a list. Python makes this distinction clear: a list is ordered, a set is not.
Lighter-weight, immutable collections have a use case. The code in OP appears to be one where it makes sense. I follow the rule where variables are mutable IFF they need to be mutable.
Even in Haskell, though, people often write all kinds of type-class magic to allow "iterating" over a tuple. For example, a Binary instance over a tuple wants to call "put" on each element.
Haskell's (Oleg's) HList is basically a tuple with iteration/list-like operations.
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?What breaks is something like:
def foo(default_arg = slow_f()):
pass
Under the shorthand gets turned into: ParamNone = object()
def foo(default_arg = ParamNone):
if default_arg is ParamNone:
default_arg = slow_f()
pass
This is fine, since everyone would know that the shorthand means to not put slow code there. Instead, people will start writing it as: _foo_arg = slow_f()
def foo(default_arg = _foo_arg):
pass
Of course, then what happens with: _foo_arg = slow_f()
def foo(default_arg = _foo_arg):
_foo_arg = 5
? Under expansion it becomes: _foo_arg = slow_f()
def foo(default_arg = ParamNone):
if default_arg is ParamNone:
default_arg = _foo_arg
_foo_arg.add(5)
This violates Python's scoping rules, because _foo_arg is now being used in local scope instead of global scope. Eg: >>> def f(x=None):
... if x is None:
... x = spam
... spam = 3
...
>>> spam = 9
>>>
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in f
UnboundLocalError: local variable 'spam' referenced before assignment
Which means you now need a new scoping rule, just to handle default parameters without making things more confusing.It also turns what was a simple O(1) offset into a precomputed list into a globals() lookup for many cases.
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.
There are other ways to emphasize it ought to be a dict/mappable. Change its name to be suffixed as "_dict", for example?