Return and set
81282ed9a88799d21e77957df2d84bd6514d9af6 at myhashismyemail.com
Tue Jul 19 15:52:52 CEST 2011
On 07/19/2011 09:43 AM, Ben Finney wrote:
> Billy Mays
> <81282ed9a88799d21e77957df2d84bd6514d9af6 at myhashismyemail.com> 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
This function is used in a file parser. There are two methods,
getToken() and peekToken(). getToken pops a token from the file, while
peekToken keeps the token, but still returns it.
t = self.tok
self.tok = None
t = self.gen.next()
if not self.tok:
self.tok = self.getToken()
NULL is an enumerated value I have defined above. The idea is for
peekToken to reuse getToken, but to keep the token still around.
More information about the Python-list