Suggestions for good programming practices?
Bengt Richter
bokr at oz.net
Tue Jun 25 15:14:22 EDT 2002
On 24 Jun 2002 23:16:02 -0400, aahz at pythoncraft.com (Aahz) wrote:
>In article <mailman.1024951532.5616.python-list at python.org>,
>David LeBlanc <whisper at oz.net> wrote:
>>Mark:
>>>
>>> When evaluating whether a variable is None, don't compare it like this:
>>>
>>> if x == None:
>>>
>>> instead, use:
>>>
>>> if x:
>>>
>>> or:
>>>
>>> if not x:
>>>
>>> The encourages a polymorphic approach. If you must compare to
>>> None, use the identify operator rather than equality:
>>>
>>> if x is None:
>>>
>>> or:
>>>
>>> if x is not None:
>>
>>I'm curious to know how this encourages polymorphism, and how making a
>>conditional test implicit rather then explicit is good practice?
>
>Depends on what you're testing for. One of the big features of Python's
>object model is that any "empty" object tests as false: None, 0, "", (),
>[], and {}. Testing for a specific false value (such as 0 or None)
>prevents you from easily changing the object being used. Rely on the
>object to tell you whether it's true or false, and you'll be fine.
>
>That's polymorphic.
This kind of usage seems common:
>>> def foo(x=None):
... if x: print "Aahz says we'll be fine with %s" % `x`
... else: print "But what about %s ?" % `x`
... if x is None: print "Here we know we were passed %s (maybe by default)" % `x`
...
>>> foo('something')
Aahz says we'll be fine with 'something'
>>> foo(0)
But what about 0 ?
>>> foo()
But what about None ?
Here we know we were passed None (maybe by default)
Do you recommend using def foo(*args) and testing len(args) instead?
Regards,
Bengt Richter
More information about the Python-list
mailing list