diff --git a/py/__init__.py b/py/__init__.py index ccf03373c..378cce9bb 100644 --- a/py/__init__.py +++ b/py/__init__.py @@ -152,6 +152,7 @@ initpkg(__name__, 'builtin._isbytes' : ('./builtin/builtin31.py', '_isbytes'), 'builtin._istext' : ('./builtin/builtin31.py', '_istext'), 'builtin._getimself' : ('./builtin/builtin31.py', '_getimself'), + 'builtin._getcode' : ('./builtin/builtin31.py', '_getcode'), 'builtin.builtins' : ('./builtin/builtin31.py', 'builtins'), 'builtin.execfile' : ('./builtin/builtin31.py', 'execfile'), 'builtin.callable' : ('./builtin/builtin31.py', 'callable'), diff --git a/py/builtin/builtin31.py b/py/builtin/builtin31.py index 29821e4e1..382993481 100644 --- a/py/builtin/builtin31.py +++ b/py/builtin/builtin31.py @@ -22,6 +22,9 @@ if sys.version_info >= (3, 0): def _getimself(function): return getattr(function, '__self__', None) + def _getcode(function): + return function.__code__ + def execfile(fn, globs=None, locs=None): if globs is None: back = sys._getframe(1) @@ -35,7 +38,8 @@ if sys.version_info >= (3, 0): source = fp.read() finally: fp.close() - exec_(source, globs, locs) + co = compile(source, fn, "exec", dont_inherit=True) + exec_(co, globs, locs) def callable(obj): return hasattr(obj, "__call__") @@ -57,6 +61,9 @@ else: def _getimself(function): return getattr(function, 'im_self', None) + def _getcode(function): + return function.func_code + import __builtin__ as builtins def print_(*args, **kwargs): """ minimal backport of py3k print statement. """ diff --git a/py/builtin/testing/test_builtin.py b/py/builtin/testing/test_builtin.py index 87ea44cbf..6f885cabe 100644 --- a/py/builtin/testing/test_builtin.py +++ b/py/builtin/testing/test_builtin.py @@ -94,10 +94,11 @@ def test_print_simple(): def test_execfile(tmpdir): test_file = tmpdir.join("test.py") - test_file.write("x = y") + test_file.write("x = y\ndef f(): pass") ns = {"y" : 42} py.builtin.execfile(str(test_file), ns) assert ns["x"] == 42 + assert py.builtin._getcode(ns["f"]).co_filename == str(test_file) class A: y = 3 x = 4