Suggestions for good programming practices?
Jonathan Hogg
jonathan at onegoodidea.com
Thu Jun 27 09:18:40 EDT 2002
On 26/6/2002 20:53, in article afd648$3b4$0 at 216.39.172.122, "Bengt Richter"
<bokr at oz.net> wrote:
> LOL ;-)
It continually amazes me that Python is so backward as to require the
programmer to explicitly note that a function takes arguments ;-)
> ISTM caller-friendly is good, but the *args implementation of this overloading
> is not as nice
> as it could be. Is it better to allow foo(x,y,s) and foo(s) via overloaded
> foo() than, e.g.,
> to use separate names like fooxy(x,y,s) and foo(s), and have foo() call
> fooxy()?
> (That, at least, is an OT question ;-)
I'm of the opinion that when a function can take a sensible set of unrelated
optional arguments they should be keyword arguments, and one should call the
function with those keywords explicitly:
>>> def writeString( s, x=0, y=0 ):
... pass
...
>>> writeString( "Hello World" )
>>> writeString( "This is a test", x=10, y=35 )
>>>
When the function can take a variable number of related arguments, I use
*args:
>>> def writeStrings( *strings ):
... for s in strings:
... writeString( s )
...
>>> writeStrings( "Hello World" )
>>> writeStrings( "This is a test", "I love tests" )
>>>
These styles, of course, can be mixed. I'm not a big fan of the idea of
distinguishing between not supplying an optional argument and supplying the
equivalent default. I think a default should mean a default, not an
indicator of no-argument. I don't much like:
>>> def writeString( s, x=None, y=None ):
... if x is None:
... # do something else
... pass
... pass
...
I think that calling a function with a default argument explicitly given
should always make sense, i.e., read sensibly. So:
>>> writeString( "This is a test", x=None, y=None )
>>>
doesn't feel right to me since I'm not convinced that 'None' makes sense as
a position. If the default is being used to indicate, for example, the
current cursor position, then it should be explicitly named like:
>>> class _CurrentPosition: pass
...
>>> CurrentPosition = _CurrentPosition()
>>>
>>> def writeString( s, x=CurrentPosition, y=CurrentPosition ):
... if x is CurrentPosition:
... # obtain current x co-ordinate
... pass
... pass
...
>>> writeString( "Hello World", x=CurrentPosition, y=CurrentPosition )
>>>
The exception that proves the rule is where None really is a sensible
default.
Hoo hah. That's enough of that.
Jonathan
More information about the Python-list
mailing list