Python six.get_function_code() Examples
The following are 24
code examples of six.get_function_code().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
six
, or try the search function
.
Example #1
Source File: raw_building.py From linter-pylama with MIT License | 6 votes |
def _build_from_function(node, name, member, module): # verify this is not an imported function try: code = six.get_function_code(member) except AttributeError: # Some implementations don't provide the code object, # such as Jython. code = None filename = getattr(code, 'co_filename', None) if filename is None: assert isinstance(member, object) object_build_methoddescriptor(node, member, name) elif filename != getattr(module, '__file__', None): attach_dummy_node(node, name, member) else: object_build_function(node, member, name)
Example #2
Source File: test_utils.py From profiling with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_frame_stack(): def to_code_names(frames): code_names = deque() for frame in reversed(frames): code_name = frame.f_code.co_name if code_name not in mock_code_names: break code_names.appendleft(code_name) return list(code_names) baz_frame = foo() foo_frame = baz_frame.f_back.f_back frames = frame_stack(baz_frame) assert to_code_names(frames) == ['foo', 'bar', 'baz'] # base frame. frames = frame_stack(baz_frame, base_frame=foo_frame) assert to_code_names(frames) == ['bar', 'baz'] # ignored codes. frames = frame_stack(baz_frame, ignored_codes=[ six.get_function_code(foo), six.get_function_code(baz), ]) assert to_code_names(frames) == ['bar']
Example #3
Source File: core.py From jams with ISC License | 6 votes |
def deprecated(version, version_removed): '''This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.''' def __wrapper(func, *args, **kwargs): '''Warn the user, and then proceed.''' code = six.get_function_code(func) warnings.warn_explicit( "{:s}.{:s}\n\tDeprecated as of JAMS version {:s}." "\n\tIt will be removed in JAMS version {:s}." .format(func.__module__, func.__name__, version, version_removed), category=DeprecationWarning, filename=code.co_filename, lineno=code.co_firstlineno + 1 ) return func(*args, **kwargs) return decorator(__wrapper)
Example #4
Source File: testing_utils.py From tools-python with Apache License 2.0 | 6 votes |
def make_decorator(func): """ Wraps a test decorator so as to properly replicate metadata of the decorated function, including nose's additional stuff (namely, setup and teardown). """ def decorate(newfunc): if hasattr(func, 'compat_func_name'): name = func.compat_func_name else: name = func.__name__ newfunc.__dict__ = func.__dict__ newfunc.__doc__ = func.__doc__ newfunc.__module__ = func.__module__ if not hasattr(newfunc, 'compat_co_firstlineno'): newfunc.compat_co_firstlineno = six.get_function_code(func).co_firstlineno try: newfunc.__name__ = name except TypeError: # can't set func name in 2.3 newfunc.compat_func_name = name return newfunc return decorate
Example #5
Source File: test_six.py From six with MIT License | 5 votes |
def test_get_function_code(): def f(): pass assert isinstance(six.get_function_code(f), types.CodeType) if not hasattr(sys, "pypy_version_info"): pytest.raises(AttributeError, six.get_function_code, hasattr)
Example #6
Source File: test_six.py From data with GNU General Public License v3.0 | 5 votes |
def test_get_function_code(): def f(): pass assert isinstance(six.get_function_code(f), types.CodeType) if not hasattr(sys, "pypy_version_info"): py.test.raises(AttributeError, six.get_function_code, hasattr)
Example #7
Source File: test_six.py From data with GNU General Public License v3.0 | 5 votes |
def test_get_function_code(): def f(): pass assert isinstance(six.get_function_code(f), types.CodeType) if not hasattr(sys, "pypy_version_info"): py.test.raises(AttributeError, six.get_function_code, hasattr)
Example #8
Source File: host_test_scheme.py From mbed-os-tools with Apache License 2.0 | 5 votes |
def test_host_test_class_test_attr_callable_args_num(self): """ Check if host test has callable setup(), result() and teardown() class member has 2 arguments """ for i, ht_name in enumerate(self.HOSTREGISTRY.HOST_TESTS): ht = self.HOSTREGISTRY.HOST_TESTS[ht_name] if ht and hasattr(ht, 'setup') and callable(getattr(ht, 'setup')): self.assertEqual(1, six.get_function_code(ht.setup).co_argcount) if ht and hasattr(ht, 'result') and callable(getattr(ht, 'result')): self.assertEqual(1, six.get_function_code(ht.result).co_argcount) if ht and hasattr(ht, 'teardown') and callable(getattr(ht, 'teardown')): self.assertEqual(1, six.get_function_code(ht.teardown).co_argcount)
Example #9
Source File: host_test_scheme.py From mbed-os-tools with Apache License 2.0 | 5 votes |
def test_host_test_class_test_attr_callable_args_num(self): """ Check if host test has callable setup(), result() and teardown() class member has 2 arguments """ for i, ht_name in enumerate(self.HOSTREGISTRY.HOST_TESTS): ht = self.HOSTREGISTRY.HOST_TESTS[ht_name] if ht and hasattr(ht, 'setup') and callable(getattr(ht, 'setup')): self.assertEqual(1, six.get_function_code(ht.setup).co_argcount) if ht and hasattr(ht, 'result') and callable(getattr(ht, 'result')): self.assertEqual(1, six.get_function_code(ht.result).co_argcount) if ht and hasattr(ht, 'teardown') and callable(getattr(ht, 'teardown')): self.assertEqual(1, six.get_function_code(ht.teardown).co_argcount)
Example #10
Source File: injector.py From bazarr with GNU General Public License v3.0 | 5 votes |
def fix_js_args(func): '''Use this function when unsure whether func takes this and arguments as its last 2 args. It will append 2 args if it does not.''' fcode = six.get_function_code(func) fargs = fcode.co_varnames[fcode.co_argcount - 2:fcode.co_argcount] if fargs == ('this', 'arguments') or fargs == ('arguments', 'var'): return func code = append_arguments(six.get_function_code(func), ('this', 'arguments')) return types.FunctionType( code, six.get_function_globals(func), func.__name__, closure=six.get_function_closure(func))
Example #11
Source File: test_six.py From c4ddev with MIT License | 5 votes |
def test_get_function_code(): def f(): pass assert isinstance(six.get_function_code(f), types.CodeType) if not hasattr(sys, "pypy_version_info"): py.test.raises(AttributeError, six.get_function_code, hasattr)
Example #12
Source File: utils.py From barbican with Apache License 2.0 | 5 votes |
def construct_new_test_function(original_func, name, build_params): """Builds a new test function based on parameterized data. :param original_func: The original test function that is used as a template :param name: The fullname of the new test function :param build_params: A dictionary or list containing args or kwargs for the new test :return: A new function object """ new_func = types.FunctionType( six.get_function_code(original_func), six.get_function_globals(original_func), name=name, argdefs=six.get_function_defaults(original_func), closure=six.get_function_closure(original_func) ) for key, val in original_func.__dict__.items(): if key != 'build_data': new_func.__dict__[key] = val # Support either an arg list or kwarg dict for our data build_args = build_params if isinstance(build_params, list) else [] build_kwargs = build_params if isinstance(build_params, dict) else {} # Build a test wrapper to execute with our kwargs def test_wrapper(func, test_args, test_kwargs): @functools.wraps(func) def wrapper(self): return func(self, *test_args, **test_kwargs) return wrapper return test_wrapper(new_func, build_args, build_kwargs)
Example #13
Source File: utils.py From python-barbicanclient with Apache License 2.0 | 5 votes |
def construct_new_test_function(original_func, name, build_params): """Builds a new test function based on parameterized data. :param original_func: The original test function that is used as a template :param name: The fullname of the new test function :param build_params: A dictionary or list containing args or kwargs for the new test :return: A new function object """ new_func = types.FunctionType( six.get_function_code(original_func), six.get_function_globals(original_func), name=name, argdefs=six.get_function_defaults(original_func) ) # Support either an arg list or kwarg dict for our data build_args = build_params if isinstance(build_params, list) else [] build_kwargs = build_params if isinstance(build_params, dict) else {} # Build a test wrapper to execute with our kwargs def test_wrapper(func, test_args, test_kwargs): @functools.wraps(func) def wrapper(self): return func(self, *test_args, **test_kwargs) return wrapper return test_wrapper(new_func, build_args, build_kwargs)
Example #14
Source File: absltest.py From abseil-py with Apache License 2.0 | 5 votes |
def _is_in_app_main(): # type: () -> bool """Returns True iff app.run is active.""" f = sys._getframe().f_back # pylint: disable=protected-access while f: if f.f_code == six.get_function_code(app.run): # pytype: disable=wrong-arg-types return True f = f.f_back return False
Example #15
Source File: bytecode.py From pwnypack with MIT License | 5 votes |
def from_function(cls, f, *args, **kwargs): """ Create a new instance from a function. Gets the code object from the function and passes it and any other specified parameters to :meth:`from_code`. Arguments: f(function): The function to get the code object from. Returns: CodeObject: A new :class:`CodeObject` instance. """ return cls.from_code(six.get_function_code(f), *args, **kwargs)
Example #16
Source File: utils.py From sgx-kms with Apache License 2.0 | 5 votes |
def construct_new_test_function(original_func, name, build_params): """Builds a new test function based on parameterized data. :param original_func: The original test function that is used as a template :param name: The fullname of the new test function :param build_params: A dictionary or list containing args or kwargs for the new test :return: A new function object """ new_func = types.FunctionType( six.get_function_code(original_func), six.get_function_globals(original_func), name=name, argdefs=six.get_function_defaults(original_func) ) for key, val in original_func.__dict__.items(): if key != 'build_data': new_func.__dict__[key] = val # Support either an arg list or kwarg dict for our data build_args = build_params if isinstance(build_params, list) else [] build_kwargs = build_params if isinstance(build_params, dict) else {} # Build a test wrapper to execute with our kwargs def test_wrapper(func, test_args, test_kwargs): @functools.wraps(func) def wrapper(self): return func(self, *test_args, **test_kwargs) return wrapper return test_wrapper(new_func, build_args, build_kwargs)
Example #17
Source File: base.py From xbmc-addons-chinese with GNU General Public License v2.0 | 5 votes |
def __init__(self, func, prototype=None, extensible=True, source=None): cand = fix_js_args(func) has_scope = cand is func func = cand self.argcount = six.get_function_code(func).co_argcount - 2 - has_scope self.code = func self.source = source if source else '{ [python code] }' self.func_name = func.__name__ if not func.__name__.startswith('PyJs_anonymous') else '' self.extensible = extensible self.prototype = prototype self.own = {} #set own property length to the number of arguments self.define_own_property('length', {'value': Js(self.argcount), 'writable': False, 'enumerable': False, 'configurable': False}) if self.func_name: self.define_own_property('name', {'value': Js(self.func_name), 'writable': False, 'enumerable': False, 'configurable': True}) # set own prototype proto = Js({}) # constructor points to this function proto.define_own_property('constructor',{'value': self, 'writable': True, 'enumerable': False, 'configurable': True}) self.define_own_property('prototype', {'value': proto, 'writable': True, 'enumerable': False, 'configurable': False})
Example #18
Source File: injector.py From xbmc-addons-chinese with GNU General Public License v2.0 | 5 votes |
def fix_js_args(func): '''Use this function when unsure whether func takes this and arguments as its last 2 args. It will append 2 args if it does not.''' fcode = six.get_function_code(func) fargs = fcode.co_varnames[fcode.co_argcount-2:fcode.co_argcount] if fargs==('this', 'arguments') or fargs==('arguments', 'var'): return func code = append_arguments(six.get_function_code(func), ('this','arguments')) return types.FunctionType(code, six.get_function_globals(func), func.__name__, closure=six.get_function_closure(func))
Example #19
Source File: injector.py From addon with GNU General Public License v3.0 | 5 votes |
def fix_js_args(func): '''Use this function when unsure whether func takes this and arguments as its last 2 args. It will append 2 args if it does not.''' fcode = six.get_function_code(func) fargs = fcode.co_varnames[fcode.co_argcount - 2:fcode.co_argcount] if fargs == ('this', 'arguments') or fargs == ('arguments', 'var'): return func code = append_arguments(six.get_function_code(func), ('this', 'arguments')) return types.FunctionType( code, six.get_function_globals(func), func.__name__, closure=six.get_function_closure(func))
Example #20
Source File: naming.py From tangent with Apache License 2.0 | 5 votes |
def _adjoint_name(func, wrt, template): if not isinstance(func, types.FunctionType): raise TypeError varnames = six.get_function_code(func).co_varnames return template.format(func.__name__, ''.join(varnames[i] for i in wrt))
Example #21
Source File: naming.py From tangent with Apache License 2.0 | 5 votes |
def primal_name(func, wrt): """Name for the primal of a function.""" if not isinstance(func, types.FunctionType): raise TypeError(func) varnames = six.get_function_code(func).co_varnames return PRIMAL_NAME.format(func.__name__, ''.join(varnames[i] for i in wrt))
Example #22
Source File: base.py From bazarr with GNU General Public License v3.0 | 4 votes |
def __init__(self, func, prototype=None, extensible=True, source=None): cand = fix_js_args(func) has_scope = cand is func func = cand self.argcount = six.get_function_code(func).co_argcount - 2 - has_scope self.code = func self.source = source if source else '{ [python code] }' self.func_name = func.__name__ if not func.__name__.startswith( 'PyJs_anonymous') else '' self.extensible = extensible self.prototype = prototype self.own = {} #set own property length to the number of arguments self.define_own_property( 'length', { 'value': Js(self.argcount), 'writable': False, 'enumerable': False, 'configurable': False }) if self.func_name: self.define_own_property( 'name', { 'value': Js(self.func_name), 'writable': False, 'enumerable': False, 'configurable': True }) # set own prototype proto = Js({}) # constructor points to this function proto.define_own_property( 'constructor', { 'value': self, 'writable': True, 'enumerable': False, 'configurable': True }) self.define_own_property( 'prototype', { 'value': proto, 'writable': True, 'enumerable': False, 'configurable': False })
Example #23
Source File: base.py From addon with GNU General Public License v3.0 | 4 votes |
def __init__(self, func, prototype=None, extensible=True, source=None): cand = fix_js_args(func) has_scope = cand is func func = cand self.argcount = six.get_function_code(func).co_argcount - 2 - has_scope self.code = func self.source = source if source else '{ [python code] }' self.func_name = func.__name__ if not func.__name__.startswith( 'PyJs_anonymous') else '' self.extensible = extensible self.prototype = prototype self.own = {} #set own property length to the number of arguments self.define_own_property( 'length', { 'value': Js(self.argcount), 'writable': False, 'enumerable': False, 'configurable': False }) if self.func_name: self.define_own_property( 'name', { 'value': Js(self.func_name), 'writable': False, 'enumerable': False, 'configurable': True }) # set own prototype proto = Js({}) # constructor points to this function proto.define_own_property( 'constructor', { 'value': self, 'writable': True, 'enumerable': False, 'configurable': True }) self.define_own_property( 'prototype', { 'value': proto, 'writable': True, 'enumerable': False, 'configurable': False })
Example #24
Source File: base_host_test.py From mbed-os-tools with Apache License 2.0 | 4 votes |
def register_callback(self, key, callback, force=False): """! Register callback for a specific event (key: event name) @param key String with name of the event @param callback Callable which will be registstered for event "key" @param force God mode """ # Non-string keys are not allowed if type(key) is not str: raise TypeError("event non-string keys are not allowed") # And finally callback should be callable if not callable(callback): raise TypeError("event callback should be callable") # Check if callback has all three required parameters (key, value, timestamp) # When callback is class method should have 4 arguments (self, key, value, timestamp) if ismethod(callback): arg_count = six.get_function_code(callback).co_argcount if arg_count != 4: err_msg = "callback 'self.%s('%s', ...)' defined with %d arguments"% (callback.__name__, key, arg_count) err_msg += ", should have 4 arguments: self.%s(self, key, value, timestamp)"% callback.__name__ raise TypeError(err_msg) # When callback is just a function should have 3 arguments func(key, value, timestamp) if isfunction(callback): arg_count = six.get_function_code(callback).co_argcount if arg_count != 3: err_msg = "callback '%s('%s', ...)' defined with %d arguments"% (callback.__name__, key, arg_count) err_msg += ", should have 3 arguments: %s(key, value, timestamp)"% callback.__name__ raise TypeError(err_msg) if not force: # Event starting with '__' are reserved if key.startswith('__'): raise ValueError("event key starting with '__' are reserved") # We predefined few callbacks you can't use if key in self.__restricted_callbacks: raise ValueError("we predefined few callbacks you can't use e.g. '%s'"% key) self.__callbacks[key] = callback