Skip to content Skip to sidebar Skip to footer

Check If A Function Uses A Specific Keyword Argument

I've got a decorator like this: def auth(func): def dec(self, *args): user = Auth.auth(self.server.parse_params(), self.server.client_address) // snip...

Solution 1:

You can parse to source of the function being called and check how many times the user variable is being used, if it is greater than 1 then you can call that function with the variable user:

import ast
import inspect


defis_variable_used(func, variable):
    source = inspect.getsource(func).split('\n', 1)[1]  # Split to drop the decorator partreturnsum(node.id == variable for node in ast.walk(ast.parse(source))
               ifisinstance(node, ast.Name)) > 1defauth(func):
    defdec(self, *args):
        if is_variable_used(func, 'user'):
            print'Calling {func_name} with user.'.format(func_name=func.__name__)
            return func(self, user=100)
        else:
            print'Calling {func_name} without user.'.format(func_name=func.__name__)
            return func(self)
    return dec


@authdeffunc1_with_user(foo, user=None):
    return10 + user

@authdeffunc2_with_user(foo, user=None):
    a = 10 + foo
    b = a + foo
    c = a + b + user
    return a + b + c

@authdeffunc1_without_user(foo, user=None):
    pass@authdeffunc2_without_user(foo, user=None):
    return10 + foo


print func1_with_user(10)
print func2_with_user(20)
print func1_without_user(100)
print func2_without_user(200)

Output:

>>>!python so.py
Calling func1_with_user with user.
110
Calling func2_with_user with user.
260
Calling func1_without_user without user.
None
Calling func2_without_user without user.
210

Solution 2:

Why not using **kwargs? An example is this:

deff(*args, **kwargs):
    if'user'in kwargs:
        print'the given user is:', kwargs['user']
    else:
        # do something else

This way you don't have to explicitly put the parameter in the decorator, but you are able to retrieve it if the user specifies it.

Post a Comment for "Check If A Function Uses A Specific Keyword Argument"