Welcome, guest | Sign In | My Account | Store | Cart

This decorator can be used to cast argument types automatically, using a pre-specified list of types, when a function is called.

Python, 28 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class ConvertArgumentTypes(object):
    """Converts function arguments to specified types."""
    def __init__(self,*args, **kw):
        self.args = args
        self.kw = kw
    def __call__(self, f):
        def func(*args, **kw):
            nargs = [x[0](x[1]) for x in zip(self.args, args)]
            invalidkw = [x for x in kw if x not in self.kw]
            if len(invalidkw) > 0:
                raise TypeError, f.func_name + "() got an unexpected keyword argument '%s'" % invalidkw[0]
            kw = dict([(x,self.kw[x](kw[x])) for x in kw])
            v = f(*nargs, **kw)
            return v
        return func

#keyword arguments are handled normally.
@ConvertArgumentTypes(int, float, c=int, d=str)
def z(a,b,c=0,d=""):
    return a + b, (c,d)

@ConvertArgumentTypes(int, int)
def y(p,q):
    return p + q

print y("1","2")

print z(1,2,c=34,d=56)

It's not incredibly useful, but is handy in a few corner cases where you need to guarantee that your function arguments will be of a certain type.

It could also be used to apply functions automatically to arguments as a function is called. This could be useful in a data validation scenario, encouraging very loose coupling between validation functions and application logic.

Similar recipes are: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325917 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/355638

Updated: now handles keyword arguments.

Created by S W on Tue, 7 Dec 2004 (PSF)
Python recipes (4591)
S W's recipes (20)

Required Modules

  • (none specified)

Other Information and Tasks