__iadd__ and fellows missing (Python 2.2)

Tim Peters tim.one at comcast.net
Sat Apr 13 23:23:30 EDT 2002


[Mike C. Fletcher]
> I was unaware that there was no guarantee for 0-length tuples always
> being unique objects.  There are lots of places in my code where I use
> 0-length tuples in this pattern:
>
> NULL = ()
>
> class A:
> 	def b( self, object=NULL ):
> 		if object is NULL:
> 			#was not specified
> 		elif object is None:
> 			#specified to be object None

Mike, I'm pretty lost.  Are you saying that if a user explicitly calls

    A().b(())

or

    A().b((1, 2, 3)[2:2])

you *want* to hit the "was not specified" block?  That's all a guarantee
about 0-length tuples would buy you.  But if it's not what you want, such a
guarantee is irrelevant:  the method is full of holes regardless of whether
the empty tuple is unique.

Note that default arguments aren't designed to tell you whether a specific
argument was explicitly passed.  They're designed to supply reasonable
defaults that a user could just as well pass explicitly if they feel like
it.  Rather than invent more brittle tricks, I suggest pondering whether the
intended use of this gimmick isn't good enough for your purposes (and noting
that it's always been good enough for mine).

If you really need to know whether a thing was passed explicitly, it makes
more sense to insist that specifying it be done via keyword, and write the
function to examine the keys in the keyword dict passed to it.  It's all
obvious then.

    def f(required, **kw):
        if 'abc' in kw:
            print "'abc' was explicitly passed"
            abc = kw['abc']
        else:
            print "'abc' was not specified"
            abc = 42
        print "'abc' is", abc

    f(3)
    f(3, abc=666)






More information about the Python-list mailing list