• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python six.get_function_code函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中six.get_function_code函数的典型用法代码示例。如果您正苦于以下问题:Python get_function_code函数的具体用法?Python get_function_code怎么用?Python get_function_code使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_function_code函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _get_bakery_dynamic_attr

    def _get_bakery_dynamic_attr(self, attname, obj, args=None, default=None):
        """
        Allows subclasses to provide an attribute (say, 'foo') in three
        different ways: As a fixed class-level property or as a method
        foo(self) or foo(self, obj). The second argument argument 'obj' is
        the "subject" of the current Feed invocation. See the Django Feed
        documentation for details.

        This method was shamelessly stolen from the Feed class and extended
        with the ability to pass additional arguments to subclass methods.
        """
        try:
            attr = getattr(self, attname)
        except AttributeError:
            return default

        if callable(attr) or args:
            args = args[:] if args else []

            # Check co_argcount rather than try/excepting the function and
            # catching the TypeError, because something inside the function
            # may raise the TypeError. This technique is more accurate.
            try:
                code = six.get_function_code(attr)
            except AttributeError:
                code = six.get_function_code(attr.__call__)
            if code.co_argcount == 2 + len(args):  # one argument is 'self'
                args.append(obj)
            return attr(*args)

        return attr
开发者ID:datadesk,项目名称:django-bakery,代码行数:31,代码来源:feeds.py


示例2: __init__

 def __init__(self, cb, args, kwargs):
     self.callback = cb
     self.args = args or []
     self.kwargs = kwargs or {}
     self.callback_name = cb.__name__
     self.callback_filename = os.path.split(get_function_code(cb).co_filename)[-1]
     self.callback_lineno = get_function_code(cb).co_firstlineno + 1
开发者ID:adamchainz,项目名称:sure,代码行数:7,代码来源:__init__.py


示例3: test_function_attached_as_workpace_method_has_same_metainformation_as_free_function

 def test_function_attached_as_workpace_method_has_same_metainformation_as_free_function(self):
     self.assertEqual(MatrixWorkspace.rebin.__name__, simpleapi.Rebin.__name__)
     self.assertEqual(MatrixWorkspace.rebin.__doc__, simpleapi.Rebin.__doc__)
     
     # Signature of method will have extra self argument
     freefunction_sig = six.get_function_code(simpleapi.rebin).co_varnames
     expected_method_sig = ['self']
     expected_method_sig.extend(freefunction_sig)
     self.assertEqual(six.get_function_code(MatrixWorkspace.rebin).co_varnames, tuple(expected_method_sig))
开发者ID:rosswhitfield,项目名称:mantid,代码行数:9,代码来源:SimpleAPITest.py


示例4: _func_type

def _func_type(func):
    """ returns if callable is a function, method or a classmethod """
    argnames = six.get_function_code(func).co_varnames[:six.get_function_code(func).co_argcount]
    if len(argnames) > 0:
        if argnames[0] == 'self':
            return 'method'
        if argnames[0] == 'cls':
            return 'classmethod'
    return 'function'
开发者ID:infoscout,项目名称:django-cache-utils,代码行数:9,代码来源:utils.py


示例5: fix_js_args

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))
开发者ID:2mny,项目名称:mylar,代码行数:10,代码来源:injector.py


示例6: get_func_code

def get_func_code(func):
  """Returns func_code of passed callable."""
  _, func = tf_decorator.unwrap(func)
  if callable(func):
    if tf_inspect.isfunction(func) or tf_inspect.ismethod(func):
      return six.get_function_code(func)
    elif hasattr(func, '__call__'):
      return six.get_function_code(func.__call__)
    else:
      raise ValueError('Unhandled callable, type=%s' % type(func))
  else:
    raise ValueError('Argument must be callable')
开发者ID:neilireson,项目名称:tensorflow,代码行数:12,代码来源:function_utils.py


示例7: __eq__

 def __eq__(self, other):
     if self.name != other.name:
         return False
     # Functions do not define __eq__ but func_code objects apparently do.
     # (If we're wrapping some other callable, they will be responsible for
     # defining equality on their end.)
     if self.body == other.body:
         return True
     else:
         try:
             return six.get_function_code(self.body) == six.get_function_code(other.body)
         except AttributeError:
             return False
开发者ID:pyinvoke,项目名称:invoke,代码行数:13,代码来源:tasks.py


示例8: check_function_eq

def check_function_eq(func_a, func_b):
    """Check if two functions have the same bytecode."""
    code_a = six.get_function_code(func_a)
    code_b = six.get_function_code(func_b)

    # check the equality of the bytecode
    code_equality = all([getattr(code_a, prop) == getattr(code_b, prop) for
                         prop in _FUNCTION_EQUALITY_PROPERTIES])

    # check the equality of the function
    function_equality = all([func(func_b) == func(func_b) for func
                             in _FUNCTION_EQUALITY_METHODS])

    return all([code_equality, function_equality])
开发者ID:micumatei,项目名称:cloudbase-init-ci,代码行数:14,代码来源:util.py


示例9: serialize

def serialize(cust_obj):
    """A function to serialize custom objects passed to a model

    Args:
        cust_obj(callable): a custom layer or function to serialize

    Returns:
        a dict of the serialized components of the object"""
    ser_func = dict()
    if isinstance(cust_obj, types.FunctionType):

        func_code = six.get_function_code(cust_obj)
        func_code_d = dill.dumps(func_code).decode('raw_unicode_escape')
        ser_func['func_code_d'] = func_code_d
        ser_func['name_d'] = pickle.dumps(
            cust_obj.__name__).decode('raw_unicode_escape')
        ser_func['args_d'] = pickle.dumps(
            six.get_function_defaults(cust_obj)).decode('raw_unicode_escape')
        clos = dill.dumps(
            six.get_function_closure(cust_obj)).decode('raw_unicode_escape')
        ser_func['clos_d'] = clos
        ser_func['type_obj'] = 'func'
    else:
        if hasattr(cust_obj, '__module__'):  # pragma: no cover
            cust_obj.__module__ = '__main__'
        ser_func['name_d'] = None
        ser_func['args_d'] = None
        ser_func['clos_d'] = None
        ser_func['type_obj'] = 'class'
        loaded = dill.dumps(cust_obj).decode('raw_unicode_escape')
        ser_func['func_code_d'] = loaded
    return ser_func
开发者ID:tboquet,项目名称:python-alp,代码行数:32,代码来源:keras_backend.py


示例10: wrapped_target

 def wrapped_target(*args, **kwargs):
     with silk_meta_profiler():
         try:
             func_code = six.get_function_code(target)
         except AttributeError:
             raise NotImplementedError(
                 "Profile not implemented to decorate type %s" % target.__class__.__name__
             )
         line_num = func_code.co_firstlineno
         file_path = func_code.co_filename
         func_name = target.__name__
         if not self.name:
             self.name = func_name
         self.profile = {
             "func_name": func_name,
             "name": self.name,
             "file_path": file_path,
             "line_num": line_num,
             "dynamic": self._dynamic,
             "start_time": timezone.now(),
             "request": DataCollector().request,
         }
         self._start_queries()
     try:
         result = target(*args, **kwargs)
     except Exception:
         self.profile["exception_raised"] = True
         raise
     finally:
         with silk_meta_profiler():
             self.profile["end_time"] = timezone.now()
             self._finalise_queries()
     return result
开发者ID:JoshData,项目名称:silk,代码行数:33,代码来源:profiler.py


示例11: attach_func_as_method

def attach_func_as_method(name, func_obj, self_param_name, workspace_types=None):
    """
        Adds a method to the given type that calls an algorithm
        using the calling object as the input workspace

        :param name: The name of the new method as it should appear on the type
        :param func_obj: A free function object that defines the implementation of the call
        :param self_param_name: The name of the parameter in the free function that the method's self maps to
        :param workspace_types: A list of string names of a workspace types. If None, then it is attached
                              to the general Workspace type. Default=None
    """

    def _method_impl(self, *args, **kwargs):
        # Map the calling object to the requested parameter
        kwargs[self_param_name] = self
        # Define the frame containing the final variable assignment
        # used to figure out the workspace name
        kwargs["__LHS_FRAME_OBJECT__"] = _inspect.currentframe().f_back
        # Call main function
        return func_obj(*args, **kwargs)

    # ------------------------------------------------------------------
    # Add correct meta-properties for the method
    signature = ["self"]
    signature.extend(get_function_code(func_obj).co_varnames)
    customise_func(_method_impl, func_obj.__name__, tuple(signature), func_obj.__doc__)

    if workspace_types or len(workspace_types) > 0:
        for typename in workspace_types:
            cls = getattr(_api, typename)
            setattr(cls, name, _method_impl)
    else:
        setattr(_api.Workspace, name, _method_impl)
开发者ID:rosswhitfield,项目名称:mantid,代码行数:33,代码来源:_workspaceops.py


示例12: parse_args

def parse_args(args, path, query, specials):
    def one_or_many(fn_, dict_, key):
        result = [fn_(value) for value in dict_[key]]
        return result[0] if len(result) == 1 else result

    kwargs = {}
    for arg, parse_fn in six.iteritems(args):
        if arg in specials:
            kwargs[arg] = specials[arg]()
        elif parse_fn is None:
            kwargs[arg] = one_or_many(lambda x: x, query, arg)
        elif isinstance(parse_fn, tuple):
            kwargs[arg] = parse_fn[DEFAULT] if arg not in query else one_or_many(parse_fn[CALLABLE], query, arg)
        elif isalambda(parse_fn):
            _code = six.get_function_code(parse_fn)
            closures = six.get_function_closure(parse_fn)
            if closures:
                assert len(closures) <= 1
                fn = closures[0].cell_contents
            else:
                fn = eval(".".join(_code.co_names), six.get_function_globals(parse_fn))
            kwargs[arg] = fn(**parse_args(get_function_args(parse_fn), path, query, specials))
        else:
            kwargs[arg] = one_or_many(parse_fn, query, arg)
    return kwargs
开发者ID:petr-s,项目名称:cleaREST,代码行数:25,代码来源:core.py


示例13: __deepcopy__

    def __deepcopy__(self, memo=None):
        """Create and return a deep copy of this instance."""

        # Attempt to figure out from the method signature whether
        # a comparison function is expected.
        args = []
        code = six.get_function_code(self.__class__.__init__)
        if any([i.endswith('__cmp') for i in code.co_varnames]):
            args.append(self._cmp)

        # Create an empty sorted dictionary.
        answer = self.__class__(*args)

        # Ensure that this object is in our memo list, in case
        # there is a recursive relationship.
        if not memo:
            memo = {}
        memo[id(self)] = answer

        # Deep copy the individual elements.
        for key, value in six.iteritems(self):
            answer.__setitem__(
                deepcopy(key, memo=memo),
                deepcopy(value, memo=memo),
            )

        # Done.
        return answer
开发者ID:lukesneeringer,项目名称:dict-sorted,代码行数:28,代码来源:base.py


示例14: __call__

 def __call__ (self, fn, instance, args, kwargs):
   log_this = LOG.isEnabledFor (self.log_level)
   if self.log_enter and log_this:
     # Non-python methods don't have a func_code
     if self.log_args and hasattr (fn, "func_code"):
       code = six.get_function_code(fn)
       argnames = code.co_varnames[:code.co_argcount]
       x_args = args if not instance else ((instance,) + args)
       arg_str = ", ".join ("%s=%r" % entry for entry in
                            list(zip (argnames, x_args))
                            + list(kwargs.items ()))
     else: # Why?
       arg_str = "..."
     LOG.log (self.log_level, "Called: %s:%s:%s (%s)",
              fn.__class__.__name__,
              getattr (fn, "__module__", "<?module?>"),
              getattr (fn, "__name__", "<?name?>"),
              arg_str)
   if self.log_trace:
     sys.settrace (self.globaltrace)
   tic = time.time ()
   rc = fn (*args, **kwargs)
   toc = time.time ()
   if self.log_trace:
     sys.settrace (None)
   if self.log_exit and log_this:
     LOG.log (
       self.log_level,
       "Return: %s:%s:%s (...) -> %s (...)  Duration: %.6f secs  RC: %s",
       fn.__class__.__name__,
       getattr (fn, "__module__", "<?module?>"),
       getattr (fn, "__name__", "<?name?>"),
       inspect.currentframe ().f_back.f_code.co_name,
       toc - tic, rc if self.log_rc else "...")
   return rc
开发者ID:pombredanne,项目名称:logtool,代码行数:35,代码来源:log_wrap.py


示例15: replot

def replot(plot,
           agg=Count(), info=Const(val=1), shader=Id(),
           remove_original=True,
           plot_opts={}, **kwargs):
    """
    Treat the passed plot as an base plot for abstract rendering, generate the
    proper Bokeh plot based on the passed parameters.

    This is a convenience for:
    > src=source(plot, ...)
    > <plot-type>(source=src, <params>, **ar.mapping(src))

    Transfers plot title, width, height from the original plot

    plot -- Plot to based new plot off of
    remove_original -- Remove the source plot from the document (default: true)
    plot_opts -- Options passed directly to soure.
                   This parameter only needs to be used if there is a name
                   conflict bewteen  target plot type and
                   source options (see kwargs note)
    **kwargs -- Arugments for the plot or source as needed.
                If in conflict, a kwarg will be applied to the source function.
                If this causes incorrecte behavior, the plot arguments may
                be put in the plot_opts parameter instead.
    returns -- A new plot
    """

    # Remove the base plot (if requested)
    if remove_original and plot in curdoc().context.children:
        curdoc().context.children.remove(plot)

    # Sift kwargs
    source_opts = {}
    for key in ServerDataSource().vm_props():
        if key in kwargs:
            source_opts[key] = kwargs.pop(key)

    for name in get_function_code(source).co_varnames:
        if name in kwargs:
            source_opts[name] = kwargs.pop(name)

    # Transfer specific items from the source plot, then updates from kwargs
    plot_opts['plot_width'] = plot.plot_width
    plot_opts['plot_height'] = plot.plot_height
    plot_opts['title'] = plot.title
    plot_opts.update(kwargs)

    src = source(plot, agg, info, shader, **source_opts)
    plot_opts.update(mapping(src))

    if shader.out == "image":
        new_plot = image(source=src, **plot_opts)
    elif shader.out == "image_rgb":
        new_plot = image_rgba(source=src, **plot_opts)
    elif shader.out == "multi_line":
        new_plot = multi_line(source=src, **plot_opts)
    else:
        raise ValueError("Unhandled output type %s" % shader.out)

    return new_plot
开发者ID:JBurke007,项目名称:bokeh,代码行数:60,代码来源:ar_downsample.py


示例16: filter_kwargs

def filter_kwargs(_function, *args, **kwargs):
    """Given a function and args and keyword args to pass to it, call the function
    but using only the keyword arguments which it accepts.  This is equivalent
    to redefining the function with an additional \*\*kwargs to accept slop
    keyword args.

    If the target function already accepts \*\*kwargs parameters, no filtering
    is performed.

    Parameters
    ----------
    _function : callable
        Function to call.  Can take in any number of args or kwargs

    """

    if has_kwargs(_function):
        return _function(*args, **kwargs)

    # Get the list of function arguments
    func_code = six.get_function_code(_function)
    function_args = func_code.co_varnames[:func_code.co_argcount]
    # Construct a dict of those kwargs which appear in the function
    filtered_kwargs = {}
    for kwarg, value in list(kwargs.items()):
        if kwarg in function_args:
            filtered_kwargs[kwarg] = value
    # Call the function with the supplied args and the filtered kwarg dict
    return _function(*args, **filtered_kwargs)
开发者ID:rabitt,项目名称:mir_eval,代码行数:29,代码来源:util.py


示例17: construct_new_test_function

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)
开发者ID:openstack,项目名称:python-barbicanclient,代码行数:28,代码来源:utils.py


示例18: description

    def description(self, argv0='manage.py', command=None):
        '''Description outputed to console'''
        command = command or self.__class__.__name__.lower()
        import inspect
        _help = u''
        _help += u'{}\n'.format(command)
        if self.__doc__:
            _help += self._fix_docstring(self.__doc__) +'\n'
        else:
            _help += u'{}\n'.format(command)

        funcs = self.get_funcs()
        funcs.sort(key=lambda x: six.get_function_code(x[1]).co_firstlineno)

        for attr, func in funcs:
            func = getattr(self, attr)
            comm = attr.replace('command_', '', 1)
            args = inspect.getargspec(func).args[1:]
            args = (' [' + '] ['.join(args) + ']') if args else ''

            _help += "\t{} {}:{}{}\n".format(
                            argv0, command, comm, args)

            if func.__doc__:
                _help += self._fix_docstring(func.__doc__, 2)
        return _help
开发者ID:SmartTeleMax,项目名称:iktomi,代码行数:26,代码来源:base.py


示例19: execute

 def execute(self, streams):
     try:
         parser = PDFContentParser(streams)
     except PSEOF:
         # empty page
         return
     while 1:
         try:
             (_, obj) = parser.nextobject()
         except PSEOF:
             break
         if isinstance(obj, PSKeyword):
             name = keyword_name(obj)
             method = 'do_%s' % name.replace('*', '_a').replace('"', '_w').replace("'", '_q')
             if hasattr(self, method):
                 func = getattr(self, method)
                 nargs = six.get_function_code(func).co_argcount-1
                 if nargs:
                     args = self.pop(nargs)
                     logging.debug('exec: %s %r', name, args)
                     if len(args) == nargs:
                         func(*args)
                 else:
                     logging.debug('exec: %s', name)
                     func()
             else:
                 if STRICT:
                     raise PDFInterpreterError('Unknown operator: %r' % name)
         else:
             self.push(obj)
     return
开发者ID:Cybjit,项目名称:pdfminer,代码行数:31,代码来源:pdfinterp.py


示例20: repl

 def repl(self):
     while True:
         input = six.moves.input('> ')
         input = shlex.split(input)
         command = input[0]
         if command == 'quit':
             break
         for available_command in self.COMMANDS:
             if command in available_command:
                 method_name = self.COMMANDS[available_command]
                 method = getattr(self, method_name)
                 arg_count = six.get_function_code(method).co_argcount
                 if len(input) != arg_count:
                     print("Wrong argument count.")
                     print("Expected %s" % arg_count)
                     break
                 try:
                     result = method(*input[1:])
                 except Exception as e:
                     print(e)
                 else:
                     if result is not None:
                         print(result)
                 break
         else:
             print("Invalid command.")
开发者ID:BryghtShadow,项目名称:raf,代码行数:26,代码来源:__main__.py



注:本文中的six.get_function_code函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python six.get_function_defaults函数代码示例发布时间:2022-05-27
下一篇:
Python six.get_function_closure函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap