Created
February 14, 2014 23:10
-
-
Save kissgyorgy/9011477 to your computer and use it in GitHub Desktop.
Python: get argument value in a decorator by name of the argument
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
import functools | |
import Command | |
FORBIDDEN_SCHEMAS = {'public'} | |
def no_forbidden_schema(func): | |
"""Check if schema parameter is in FORBIDDEN_SCHEMAS.""" | |
@functools.wraps(func) | |
def wrapper(self, *args, **kwargs): | |
try: | |
schema = kwargs['schema'] | |
except KeyError: | |
schema_arg_index = inspect.getargspec(func).args.index('schema') | |
schema = args[schema_arg_index] | |
if schema in FORBIDDEN_SCHEMAS: | |
return 'Error: Forbidden schema!' | |
return func(self, *args, **kwargs) | |
return wrapper | |
# Usage: | |
class AddTeam(Command): | |
@no_forbidden_schema | |
def run(self, name, schema, domain): | |
pass | |
# or: | |
class AddTeam(Command): | |
@no_forbidden_schema | |
def run(self, schema, name, domain): | |
pass | |
# or: | |
class AddTeam(Command): | |
@no_forbidden_schema | |
def run(self, name, schema='guest', domain="example.com"): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment