Return and set

Ben Finney ben+python at
Tue Jul 19 15:43:17 CEST 2011

Billy Mays
<81282ed9a88799d21e77957df2d84bd6514d9af6 at> writes:

> I have a method getToken() which checks to see if a value is set, and
> if so, return it. However, it doesn't feel pythonic to me:

Clearly that's because the function name is not Pythonic :-)

I'll assume the name is a PEP-8 compatible ‘get_token’.

> def getToken(self):
>     if self.tok:
>         t = self.tok
>         self.tok = None
>         return t
>     # ...

Are you testing ‘self.tok’ in a boolean context because you don't care
whether it it might be ‘""’ or ‘0’ or ‘0.0’ or ‘[]’ or ‘False’ or lots
of other things that evaluate false in a boolean context?

If you want to test whether it is any value other than ‘None’, that's
not the way to do it. Instead, use ‘if self.token is not None’.

But I don't see why you test it at all, in that case, since you're
immediately setting it to ‘None’ afterward.

Also, the function name is quite misleading; the implication for a
function named ‘get_foo’ is that it is a non-destructive read. I would
expect the name of this function to indicate what's going on much more

My suggestion::

    def get_and_reset_token(self):
        result = self.token
        self.token = None
        return result

 \      “I stayed up all night playing poker with tarot cards. I got a |
  `\                  full house and four people died.” —Steven Wright |
_o__)                                                                  |
Ben Finney

More information about the Python-list mailing list