Anonymous class question

Carl Banks imbosol at
Thu Aug 7 05:20:24 CEST 2003

Dan Williams wrote:
> Python experts,
> Is there a more pythonic way to do something evquilent to what this line 
> does without creating a dummy class?
> self.file = type("", (object,), {'close':lambda slf: None})()
> As you can guess, I want a dummy object that I can call close on with 
> impunity.

The above line does create a dummy class.  What's your motivation for
doing this--what's wrong with defining a dummy class?  Is there a
reason you want it to be nameless?  Do you want to do this simply to
save typing?  Do you have hundreds of these dummy classes and don't
want to type a new class each time?  The Pythonic way is to wrap it in
a function:

    def nameless_dummy_object_with_methods(*methods):
        d = {}
        for sym in methods:
            d[sym] = lambda self,*args,**kwargs: None
        return type("",(object,),d)()

    self.file = nameless_dummy_object_with_methods('close')

You specify any methods you want as strings and the functions builds a
class with those methds, which quietly accept any arguments they are
passed, and returns an instance of it.  Presumably, the code works
with regular objects, and trying to define the right "prototype" for
each method is doing unnecessary work.

"You don't run Microsoft Windows.  Microsoft Windows runs you."

More information about the Python-list mailing list