Created
November 5, 2014 01:37
-
-
Save mdippery/0f634224afcd09af5986 to your computer and use it in GitHub Desktop.
Python decorator that inserts variables into a function
This file contains 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 sys | |
from functools import wraps | |
from types import FunctionType | |
def is_python3(): | |
return sys.version_info >= (3, 0) | |
def more_vars(**extras): | |
def wrapper(f): | |
@wraps(f) | |
def wrapped(*args, **kwargs): | |
fn_globals = {} | |
fn_globals.update(globals()) | |
fn_globals.update(extras) | |
if is_python3(): | |
func_code = '__code__' | |
else: | |
func_code = 'func_code' | |
call_fn = FunctionType(getattr(f, func_code), fn_globals) | |
return call_fn(*args, **kwargs) | |
return wrapped | |
return wrapper | |
@more_vars(a="hello", b="world") | |
def test(x, y): | |
print("locals: {}".format(locals())) | |
print("x: {}".format(x)) | |
print("y: {}".format(y)) | |
print("a: {}".format(a)) | |
print("b: {}".format(b)) | |
if __name__ == "__main__": | |
test(1, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment