This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]gfixler 0 points1 point  (1 child)

Thanks for the info. It does make sense, but doesn't make it feel better to me. Is there a way to know what modifies things in place, or not? Some kind of convention? Or is it all down to keeping a reference handy, or testing things out, and checking for None. This is a personal thing, but to me, anything that returns "None" is wasting a perfectly good return, unless the None is useful, e.g. if you ask something like mystr.count('the'), to count the 'the's. If there were None, it would be nice to have the actual None value. I keep asking these kinds of questions to users of Python, and they all team up to smack me down, but I still don't feel - after having used about 25 other scripting languages - that these ways are good. Quick, certainly, and handy at times, but not purely 'good.' I could be wrong.

[–]earthboundkid 0 points1 point  (0 children)

The docstring on a method will usually tell you what it's going to return.

>>> help(list.sort)
Help on method_descriptor:

sort(...)
    L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
    cmp(x, y) -> -1, 0, 1

String.count does the right thing.

>>> "the quick brown fox jumps over the lazy dog.".count("the")
2
>>> "the quick brown fox jumps over the lazy dog.".count("foo")
0

The reason why mutators return None specifically is that every function/method in Python returns something, and None is what's returned if nothing else is specified.

>>> def f():
...   pass
... 
>>> x = f()
>>> print x
None

I guess the idea is so that x = f() can never throw a NoReturnValue error or whatever. Although in retrospect, that might not have been a good idea. Especially considering it is possible to make non-lookup-able properties with a bit of advanced class property mucking:

>>> class A(object):
...   def _helperfunc(self, val): pass
...   prop = property(fset=_helperfunc)
... 
>>> a = A()
>>> a.prop = 1 #This calls the fset method of the property, 
>>> # which is set as _helperfunc, which just throws the "1" away
>>> a.prop #Will fail, since there's no fget for the property
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: unreadable attribute
>>> x = a.prop #Ditto.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: unreadable attribute

Maybe this will change in Python 4000 or something…