how to assert that method accepts specific types

Darren Dale dsdale24 at gmail.com
Fri Feb 20 20:43:46 EST 2009


On Feb 20, 8:20 pm, Chris Rebert <c... at rebertia.com> wrote:
> On Fri, Feb 20, 2009 at 5:12 PM, Darren Dale <dsdal... at gmail.com> wrote:
> > I would like to assert that a method accepts certain types. I have a
> > short example that works:
>
> > from functools import wraps
>
> > def accepts(*types):
> >    def check_accepts(f):
> >        @wraps(f)
> >        def new_f(self, other):
> >            assert isinstance(other, types), \
> >                "arg %r does not match %s" % (other, types)
> >            return f(self, other)
> >        return new_f
> >    return check_accepts
>
> > class Test(object):
>
> >    @accepts(int)
> >    def check(self, obj):
> >        print obj
>
> > t = Test()
> > t.check(1)
>
> > but now I want Test.check to accept an instance of Test as well. Does
> > anyone know how this can be accomplished? The following class
> > definition for Test raises a NameError:
>
> > class Test(object):
>
> >    @accepts(int, Test)
> >    def check(self, obj):
> >        print obj
>
> You're going to have to either inject it after the class definition
> somehow, or give the class name as a string and use eval() or similar.
> The class object doesn't exist until the entire class body has
> finished executing, so you can't refer to the class within its own
> body.

Thats too bad, thanks for clarifying.



More information about the Python-list mailing list