Default method arguments

Duncan Booth duncan.booth at invalid.invalid
Tue Nov 15 11:23:41 EST 2005


Nicola Larosa wrote:
> # use new-style classes, if there's no cogent reason to do otherwise
> class A(object):
>     def __init__(self, n):
>         self.data = n
>     def f(self, x = None)
>         # do NOT use "if not x" !
>         if x is None:
>             print self.data
>         else:
>             print x
> 

Using None might be problematic if None could be a valid argument. The 
safest way all round is to use a unique object created just for this 
purpose:

_marker = object()

class A(object):

    def __init__(self, n):
        self.data = n

    def f(self, x=_marker)
        if x is _marker:
            x = self.data
        print x



More information about the Python-list mailing list