6 ms·
Aside from the unicode thing, none of the items on that list bother me particularly much. There is one that I find really irritating though: def foo(a = [])
by stevenwei 16y ago
Aside from the unicode thing, none of the items on that list bother me particularly much. There is one that I find really irritating though:
def foo(a = [])
a.append(123)
or the class based version:
class Foo(object):
a = []
def foo(self):
a.append(123)
Neither example behaves like I would expect it to.
For a language that espouses 'there should only be one, and preferably only one, obvious way to do it', that is not obvious to me at all!
Oh, and I wish it had multi-line lambdas / blocks.
- tetha 16y agoGranted, it is not completely intuitive. However, it makes sense if you know pythons module loding mechanisms: The function definition is a statement which is evaluated at module load time, and it registers the foo-function in the module namespace. During creating the foo-function, the default-parameters are evaluated (resulting in a single list instance), and the results of this evaluation are used as default parameters in the following. That is also why something like def foo(x = random_value()) is kind of tricky and should be documented.
- zephjc 16y agofor your function example, the a=[] is not a way of initializing values per se, but is an initialized default value. If you are not passing a list reference in, and not returning anything, your function foo() without an arg does nothing. If you pass in a list reference x e.g. foo(x), x will now be [123] For your class example, this is really just a matter of remembering that any self members must be explicitly referenced as such: self.a.append(123) instead of a.append(123). I have actually grown to like this, and it helps keep it clear to others viewing your code what a ivar/method belongs to. Ruby uses @, C++ optionally uses 'this' - when I do any C++ i find myself explicitly using 'this' - its that or prefix ivars with e.g. 'm_'. Reading the Zen of Python is a good way of getting into the mindset for idiomatic Python programming
- gte910h 16y agoYeah, the def foo(a=None): if a==None: a=[] a.append(123) Is odd to get used to.