Default method arguments

Duncan Booth duncan.booth at invalid.invalid
Wed Nov 16 10:48:47 CET 2005

Steven D'Aprano wrote:
> I would like to see _marker put inside the class' scope. That prevents
> somebody from the outside scope easily passing _marker as an argument
> to instance.f. It also neatly encapsulates everything A needs within
> A. 

Surely that makes it easier for someone outside the scope to pass in 
 class A(object):
     _marker = []
     def __init__(self, n): =n
     def f(self, x = _marker):
         if x is self.__class__._marker:
             # must use "is" and not "=="
             x =
         print x
 >>> instance = A(5)
 >>> instance.f(instance._marker)

What you really want is for the marker to exist only in its own little 
universe, but the code for that is even messier:

class A(object):
    def __init__(self, n): =n
    def make_f():
        marker = object()
        def f(self, x = _marker):
            if x is _marker:
                x =
            print x
        return f
    f = make_f()

>>> instance = A(6)
>>> instance.f()

More information about the Python-list mailing list