how to assert that method accepts specific types

Rhodri James rhodri at wildebst.demon.co.uk
Sat Feb 21 01:25:08 EST 2009


On Sat, 21 Feb 2009 01:12:01 -0000, Darren Dale <dsdale24 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

An icky but relatively clear way to get around this is to gratuitously
subclass Test:

class AcceptableTest(object):
     pass

class Test(AcceptableTest):
     @accepts(int, AcceptableTest)
     def check(self, obj):
         print obj


-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list