Suggestions for good programming practices?
Jonathan Hogg
jonathan at onegoodidea.com
Wed Jun 26 05:20:38 EDT 2002
More information about the Python-list mailing list
Wed Jun 26 05:20:38 EDT 2002
- Previous message (by thread): Suggestions for good programming practices?
- Next message (by thread): Suggestions for good programming practices?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 26/6/2002 1:53, in article afb3a2$skm$0 at 216.39.172.122, "Bengt Richter" <bokr at oz.net> wrote: > Well, I meant using *args to allow detecting actual "no default-overriding > argument passed", in place of x=None. The arg list items (only x here) > don't have to remain unnamed long. E.g., > >>>> def foo(*args): > ... if len(args)==1: > ... print "We know we have one non-default arg: %s" % `args[0]` > ... x = args[0] > ... elif len(args)==0: > ... print "We can supply a default arg, even None" > ... x = None > ... else: raise TypeError,'foo() takes 0 or 1 arguments (%d given)' % > len(args) > ... print 'Effective arg was: %s' % `x` > ... I find this stuff much easier to write with a helper function: >>> def shift(): ... global _0 ... __, _0 = _0[0], _0[1:] ... return __ ... Then I can write the function 'foo' much more naturally as: >>> def foo( *args ): ... global _0; _0 = args ... try: ... x = shift() ... except IndexError: ... print 'We can supply a default arg, even None' ... x = None ... else: ... try: ... shift() ... except IndexError: ... print 'We know we have one non-default arg: %s' % `x` ... else: ... raise TypeError( 'foo() takes 0 or 1 arguments' ) ... print 'Effective arg was: %s' % `x` ... This can be further simplified by removing the '*args' nonsense altogether and defining another helper function: >>> def p( f ): ... def _p( *args ): global _0; _0 = args; f() ... return _p ... >>> def foo(): ... try: ... x = shift() [etc] ... >>> p(foo)( 'hello world' ) How did we get onto this from 'Suggestions for good programming practices'? Jonathan
- Previous message (by thread): Suggestions for good programming practices?
- Next message (by thread): Suggestions for good programming practices?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list