当前位置: 首页>>代码示例>>Python>>正文


Python inspect.isfunction方法代码示例

本文整理汇总了Python中inspect.isfunction方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.isfunction方法的具体用法?Python inspect.isfunction怎么用?Python inspect.isfunction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在inspect的用法示例。


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

示例1: describe_template_sets

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def describe_template_sets():
    """
    Print the available template sets in this demo, with a short description"
    """
    import inspect
    import sys

    # a bit of magic to get all functions in this module
    templatesets = inspect.getmembers(sys.modules[__name__], inspect.isfunction)
    for (name, obj) in templatesets:
        if name == "describe_template_sets":
            continue
        print(name, obj.__doc__, "\n")


######################################################################
# The Brill Tagger
###################################################################### 
开发者ID:rafasashi,项目名称:razzy-spinner,代码行数:20,代码来源:brill.py

示例2: get_matching_classes

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def get_matching_classes(self, loadable_class_names):
        """Get loadable classes from a list of names.

        Each name can be a full module path or the full path to a
        method that returns classes to use.  The latter behavior
        is useful to specify a method that returns a list of
        classes to use in a default case.
        """

        classes = []
        for cls_name in loadable_class_names:
            obj = importutils.import_class(cls_name)
            if self._is_correct_class(obj):
                classes.append(obj)
            elif inspect.isfunction(obj):
                # Get list of classes from a function
                for cls in obj():
                    classes.append(cls)
            else:
                error_str = 'Not a class of the correct type'
                raise exception.ClassNotFound(class_name=cls_name,
                                              exception=error_str)
        return classes 
开发者ID:openstack,项目名称:zun,代码行数:25,代码来源:loadables.py

示例3: __new__

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def __new__(cls, name, bases, attrs):
        # A list of all functions which is marked as 'is_cronjob=True'
        cron_jobs = []

        # The min_tick is the greatest common divisor(GCD) of the interval of cronjobs
        # this value would be queried by scheduler when the project initial loaded.
        # Scheudler may only send _on_cronjob task every min_tick seconds. It can reduce
        # the number of tasks sent from scheduler.
        min_tick = 0

        for each in attrs.values():
            if inspect.isfunction(each) and getattr(each, 'is_cronjob', False):
                cron_jobs.append(each)
                min_tick = fractions.gcd(min_tick, each.tick)
        newcls = type.__new__(cls, name, bases, attrs)
        newcls._cron_jobs = cron_jobs
        newcls._min_tick = min_tick
        return newcls 
开发者ID:binux,项目名称:pyspider,代码行数:20,代码来源:base_handler.py

示例4: validate

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def validate(self, value, data):
        if self.condition is None and not self._is_empty(value):
            need_validate = True
        else:
            assert isfunction(self.condition), \
                'Condition should be a function for RequiresIf validator'
            need_validate = self.condition(value, data)
        if not need_validate:
            return True

        fields = []
        for field in self.fields:
            val = data.get(field)
            if val is None or val == '':
                fields.append(field)
        if fields:
            self.put_msg(
                'For given input, fields are required: %s' % ', '.join(fields)
            )
            return False
        return True 
开发者ID:remg427,项目名称:misp42splunk,代码行数:23,代码来源:validator.py

示例5: _get_name_of_callable

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def _get_name_of_callable(cls, c):
    if inspect.ismethod(c):
      return c.im_class.__name__+'.'+c.__name__
    if inspect.isfunction(c):
      if c.__name__ == (lambda: None).__name__:
        filename = c.func_code.co_filename
        cls._ensure_file_in_cache(filename, c)
        definitions = cls._LAMBDA_CACHE[filename][c.func_code.co_firstlineno]
        assert definitions
        # If there's multiple definitions at the same line, there's not enough
        # information to distinguish which lambda c refers to, so just let
        # python's generic lambda name be used
        if len(definitions) == 1:
          return astunparse.unparse(definitions[0]).strip()
      return c.__name__
    if hasattr(c, '__call__'):
      return c.__class__.__name__+'.__call__'
    return repr(c) 
开发者ID:luci,项目名称:recipes-py,代码行数:20,代码来源:magic_check_fn.py

示例6: register_check

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def register_check(check, codes=None):
    """Register a new check object."""
    def _add_check(check, kind, codes, args):
        if check in _checks[kind]:
            _checks[kind][check][0].extend(codes or [])
        else:
            _checks[kind][check] = (codes or [''], args)
    if inspect.isfunction(check):
        args = _get_parameters(check)
        if args and args[0] in ('physical_line', 'logical_line'):
            if codes is None:
                codes = ERRORCODE_REGEX.findall(check.__doc__ or '')
            _add_check(check, args[0], codes, args)
    elif inspect.isclass(check):
        if _get_parameters(check.__init__)[:2] == ['self', 'tree']:
            _add_check(check, 'tree', codes, None)
    return check


##############################################################################
# Plugins (check functions) for physical lines
############################################################################## 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:24,代码来源:pycodestyle.py

示例7: __init__

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def __init__(self, *args, **kwargs):
            self.pan_device = kwargs.pop('pan_device', None)
            pan.xapi.PanXapi.__init__(self, *args, **kwargs)
            pred = lambda x: inspect.ismethod(x) or inspect.isfunction(x) # inspect.ismethod needed for Python2, inspect.isfunction needed for Python3
            for name, method in inspect.getmembers(
                    pan.xapi.PanXapi,
                    pred):
                # Ignore hidden methods
                if name[0] == "_":
                    continue
                # Ignore non-api methods
                if name in ('xml_result', 'xml_root', 'cmd_xml'):
                    continue

                # Wrapper method.  This is used to create
                # methods in this class that match the methods in the
                # super class, and call the super class methods inside
                # a try/except block, which allows us to check and
                # analyze the exceptions and convert them to more
                # useful exceptions than generic PanXapiErrors.
                wrapper_method = PanDevice.XapiWrapper.make_method(name, method)

                # Create method matching each public method of the base class
                setattr(PanDevice.XapiWrapper, name, wrapper_method) 
开发者ID:PaloAltoNetworks,项目名称:terraform-templates,代码行数:26,代码来源:base.py

示例8: try_serialize_handler

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def try_serialize_handler(handler):
  """Try to serialize map/reduce handler.

  Args:
    handler: handler function/instance. Handler can be a function or an
      instance of a callable class. In the latter case, the handler will
      be serialized across slices to allow users to save states.

  Returns:
    serialized handler string or None.
  """
  if (isinstance(handler, types.InstanceType) or  # old style class
      (isinstance(handler, object) and  # new style class
       not inspect.isfunction(handler) and
       not inspect.ismethod(handler)) and
      hasattr(handler, "__call__")):
    return pickle.dumps(handler)
  return None 
开发者ID:elsigh,项目名称:browserscope,代码行数:20,代码来源:util.py

示例9: is_generator

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def is_generator(obj):
  """Return true if the object is generator or generator function.

  Generator function objects provides same attributes as functions.
  See isfunction.__doc__ for attributes listing.

  Adapted from Python 2.6.

  Args:
    obj: an object to test.

  Returns:
    true if the object is generator function.
  """
  if isinstance(obj, types.GeneratorType):
    return True

  CO_GENERATOR = 0x20
  return bool(((inspect.isfunction(obj) or inspect.ismethod(obj)) and
               obj.func_code.co_flags & CO_GENERATOR)) 
开发者ID:elsigh,项目名称:browserscope,代码行数:22,代码来源:util.py

示例10: is_generator_function

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def is_generator_function(obj):
  """Return true if the object is a user-defined generator function.

  Generator function objects provides same attributes as functions.
  See isfunction.__doc__ for attributes listing.

  Adapted from Python 2.6.

  Args:
    obj: an object to test.

  Returns:
    true if the object is generator function.
  """
  CO_GENERATOR = 0x20
  return bool(((inspect.isfunction(obj) or inspect.ismethod(obj)) and
               obj.func_code.co_flags & CO_GENERATOR)) 
开发者ID:elsigh,项目名称:browserscope,代码行数:19,代码来源:util.py

示例11: applicationpolicy

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def applicationpolicy(arg: Callable) -> Callable:
    """
    Decorator for application policy method.

    Allows policy to be built up from methods
    registered for different event classes.
    """

    assert isfunction(arg), arg

    @no_type_check
    def _mutator(func):
        wrapped = singledispatch(func)

        @wraps(wrapped)
        def wrapper(*args, **kwargs):
            event = kwargs.get("event") or args[-1]
            return wrapped.dispatch(type(event))(*args, **kwargs)

        wrapper.register = wrapped.register

        return wrapper

    return _mutator(arg) 
开发者ID:johnbywater,项目名称:eventsourcing,代码行数:26,代码来源:decorators.py

示例12: encoderpolicy

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def encoderpolicy(arg=None):
    """
    Decorator for encoder policy.

    Allows default behaviour to be built up from methods
    registered for different types of things, rather than
    chain of isinstance() calls in a long if-else block.
    """

    def _mutator(func):
        wrapped = singledispatch(func)

        @wraps(wrapped)
        def wrapper(*args, **kwargs):
            obj = kwargs.get("obj") or args[-1]
            return wrapped.dispatch(type(obj))(*args, **kwargs)

        wrapper.register = wrapped.register

        return wrapper

    assert isfunction(arg), arg
    return _mutator(arg) 
开发者ID:johnbywater,项目名称:eventsourcing,代码行数:25,代码来源:transcoding_v1.py

示例13: attribute

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def attribute(getter: Callable) -> property:
    """
    When used as a method decorator, returns a property object
    with the method as the getter and a setter defined to call
    instance method __change_attribute__(), which publishes an
    AttributeChanged event.
    """
    if isfunction(getter):

        @no_type_check
        def setter(self, value):
            name = "_" + getter.__name__
            self.__change_attribute__(name=name, value=value)

        @no_type_check
        def new_getter(self):
            name = "_" + getter.__name__
            return getattr(self, name, None)

        return property(fget=new_getter, fset=setter, doc=getter.__doc__)
    else:
        raise ProgrammingError("Expected a function, got: {}".format(repr(getter))) 
开发者ID:johnbywater,项目名称:eventsourcing,代码行数:24,代码来源:decorators.py

示例14: decorator

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def decorator(target):
    """A signature-matching decorator factory."""

    def decorate(fn):
        if not inspect.isfunction(fn):
            raise Exception("not a decoratable function")
        spec = compat.inspect_getfullargspec(fn)
        names = tuple(spec[0]) + spec[1:3] + (fn.__name__,)
        targ_name, fn_name = _unique_symbols(names, 'target', 'fn')

        metadata = dict(target=targ_name, fn=fn_name)
        metadata.update(format_argspec_plus(spec, grouped=False))
        metadata['name'] = fn.__name__
        code = """\
def %(name)s(%(args)s):
    return %(target)s(%(fn)s, %(apply_kw)s)
""" % metadata
        decorated = _exec_code_in_env(code,
                                      {targ_name: target, fn_name: fn},
                                      fn.__name__)
        decorated.__defaults__ = getattr(fn, 'im_func', fn).__defaults__
        decorated.__wrapped__ = fn
        return update_wrapper(decorated, fn)
    return update_wrapper(decorate, target) 
开发者ID:jpush,项目名称:jbox,代码行数:26,代码来源:langhelpers.py

示例15: check_all_contracts

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isfunction [as 别名]
def check_all_contracts(*args, decorate_main=True) -> None:
    """Automatically check contracts for all functions and classes in the given module.

    When called with no arguments, the current module's functions and classes are checked.
    """

    modules = []
    if decorate_main:
        modules.append(sys.modules["__main__"])

    for module_name in args:
        modules.append(sys.modules.get(module_name, None))

    for module in modules:
        if not module:
            # Module name was passed in incorrectly.
            continue
        for name, value in inspect.getmembers(module):
            if inspect.isfunction(value):
                module.__dict__[name] = check_contracts(value)
            elif inspect.isclass(value):
                add_class_invariants(value) 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:24,代码来源:__init__.py


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