Python inspect 模块,ismethod() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.ismethod()

项目:python-driver    作者:bblfsh    | 项目源码 | 文件源码
def get_containing_module(value):
    """
    Return the name of the module containing the given value, or
    C{None} if the module name can't be determined.
    @rtype: L{DottedName}
    """
    if inspect.ismodule(value):
        return DottedName(value.__name__)
    elif isclass(value):
        return DottedName(value.__module__)
    elif (inspect.ismethod(value) and value.im_self is not None and
          value.im_class is ClassType): # class method.
        return DottedName(value.im_self.__module__)
    elif inspect.ismethod(value):
        return DottedName(value.im_class.__module__)
    elif inspect.isroutine(value):
        module = _find_function_module(value)
        if module is None: return None
        return DottedName(module)
    else:
        return None
项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def boundmethod(func, callback=None):
    """
    Return a weakly-bound instance method from the given bound method. If
    callback is provided and not None, the callback will be called when the
    referenced object (the method's self) is about to be finalized; the weakly-
    bound instance method will be passed to the callback.

    If func is already a weakly-bound instance method, return a new weakly-
    bound instance method to the underlying bound method.
    """
    if inspect.ismethod(func):
        return WeakBoundMethod(func, callback)
    elif isinstance(func, bound_notification):
        return WeakNotification(func, callback)
    elif isinstance(func, _WeakCallable):
        return boundmethod(getref(func), callback)
    else:
        raise TypeError("can not create weakly-bound method from '%s' object" % (type(func).__name__,))
项目:qqmbr    作者:ischurov    | 项目源码 | 文件源码
def uses_tags(self):
        members = inspect.getmembers(self, predicate=inspect.ismethod)
        handles = [member for member in members if member[0].startswith("handle_") or member[0] == 'preprocess']
        alltags = set([])
        for handle in handles:
            if handle[0].startswith("handle_"):
                alltags.add(handle[0][len("handle_"):])
            doc = handle[1].__doc__
            if not doc:
                continue
            for line in doc.splitlines():
                m = re.search(r"Uses tags:(.+)", line)
                if m:
                    tags = m.group(1).split(",")
                    tags = [tag.strip() for tag in tags]
                    alltags.update(tags)
        alltags.update(self.enumerateable_envs.keys())
        return alltags
项目:qqmbr    作者:ischurov    | 项目源码 | 文件源码
def uses_tags(self) -> set:
        members = inspect.getmembers(self, predicate=inspect.ismethod)
        handles = [member for member in members
                   if (member[0].startswith("handle_") or
                       member[0] == 'make_numbers')]
        alltags = set([])
        for handle in handles:
            if handle[0].startswith("handle_"):
                alltags.add(handle[0][len("handle_"):])
            doc = handle[1].__doc__
            if not doc:
                continue
            for line in doc.splitlines():
                m = re.search(r"Uses tags:(.+)", line)
                if m:
                    tags = m.group(1).split(",")
                    tags = [tag.strip() for tag in tags]
                    alltags.update(tags)
        alltags.update(self.enumerateable_envs.keys())
        alltags.update(self.metatags)
        return alltags
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def addWidget(self, w, name=None, scale=None):
        if not self.acceptsType(w):
            raise Exception("Widget type %s not supported by WidgetGroup" % type(w))
        if name is None:
            name = str(w.objectName())
        if name == '':
            raise Exception("Cannot add widget '%s' without a name." % str(w))
        self.widgetList[w] = name
        self.scales[w] = scale
        self.readWidget(w)

        if type(w) in WidgetGroup.classes:
            signal = WidgetGroup.classes[type(w)][0]
        else:
            signal = w.widgetGroupInterface()[0]

        if signal is not None:
            if inspect.isfunction(signal) or inspect.ismethod(signal):
                signal = signal(w)
            signal.connect(self.mkChangeCallback(w))
        else:
            self.uncachedWidgets[w] = None
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def readWidget(self, w):
        if type(w) in WidgetGroup.classes:
            getFunc = WidgetGroup.classes[type(w)][1]
        else:
            getFunc = w.widgetGroupInterface()[1]

        if getFunc is None:
            return None

        ## if the getter function provided in the interface is a bound method,
        ## then just call the method directly. Otherwise, pass in the widget as the first arg
        ## to the function.
        if inspect.ismethod(getFunc) and getFunc.__self__ is not None:  
            val = getFunc()
        else:
            val = getFunc(w)

        if self.scales[w] is not None:
            val /= self.scales[w]
        #if isinstance(val, QtCore.QString):
            #val = str(val)
        n = self.widgetList[w]
        self.cache[n] = val
        return val
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def setWidget(self, w, v):
        v1 = v
        if self.scales[w] is not None:
            v *= self.scales[w]

        if type(w) in WidgetGroup.classes:
            setFunc = WidgetGroup.classes[type(w)][2]
        else:
            setFunc = w.widgetGroupInterface()[2]

        ## if the setter function provided in the interface is a bound method,
        ## then just call the method directly. Otherwise, pass in the widget as the first arg
        ## to the function.
        if inspect.ismethod(setFunc) and setFunc.__self__ is not None:  
            setFunc(v)
        else:
            setFunc(w, v)

        #name = self.widgetList[w]
        #if name in self.cache and (self.cache[name] != v1):
            #print "%s: Cached value %s != set value %s" % (name, str(self.cache[name]), str(v1))
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def addWidget(self, w, name=None, scale=None):
        if not self.acceptsType(w):
            raise Exception("Widget type %s not supported by WidgetGroup" % type(w))
        if name is None:
            name = str(w.objectName())
        if name == '':
            raise Exception("Cannot add widget '%s' without a name." % str(w))
        self.widgetList[w] = name
        self.scales[w] = scale
        self.readWidget(w)

        if type(w) in WidgetGroup.classes:
            signal = WidgetGroup.classes[type(w)][0]
        else:
            signal = w.widgetGroupInterface()[0]

        if signal is not None:
            if inspect.isfunction(signal) or inspect.ismethod(signal):
                signal = signal(w)
            signal.connect(self.mkChangeCallback(w))
        else:
            self.uncachedWidgets[w] = None
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def readWidget(self, w):
        if type(w) in WidgetGroup.classes:
            getFunc = WidgetGroup.classes[type(w)][1]
        else:
            getFunc = w.widgetGroupInterface()[1]

        if getFunc is None:
            return None

        ## if the getter function provided in the interface is a bound method,
        ## then just call the method directly. Otherwise, pass in the widget as the first arg
        ## to the function.
        if inspect.ismethod(getFunc) and getFunc.__self__ is not None:  
            val = getFunc()
        else:
            val = getFunc(w)

        if self.scales[w] is not None:
            val /= self.scales[w]
        #if isinstance(val, QtCore.QString):
            #val = str(val)
        n = self.widgetList[w]
        self.cache[n] = val
        return val
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def describe_klass(obj):
   """ Describe the class object passed as argument,
   including its methods """

   wi('+Class: %s' % obj.__name__)

   indent()

   count = 0

   for name in obj.__dict__:
       item = getattr(obj, name)
       if inspect.ismethod(item):
           count += 1;describe_func(item, True)

   if count==0:
      wi('(No members)')

   dedent()
   print
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def describe(module):
   """ Describe the module object passed as argument
   including its classes and functions """

   wi('[Module: %s]\n' % module.__name__)

   indent()

   count = 0

   for name in dir(module):
       obj = getattr(module, name)
       if inspect.isclass(obj):
          count += 1; describe_klass(obj)
       elif (inspect.ismethod(obj) or inspect.isfunction(obj)):
          count +=1 ; describe_func(obj)
       elif inspect.isbuiltin(obj):
          count += 1; describe_builtin(obj)

   if count==0:
      wi('(No members)')

   dedent()
项目:ml-rest    作者:apinf    | 项目源码 | 文件源码
def add_handlers(self, namespace):
        """
        Add handler functions from the given `namespace`, for instance a module.

        The namespace may be a string, in which case it is expected to be a name of a module.
        It may also be a dictionary mapping names to functions.

        Only non-underscore-prefixed functions and methods are imported.

        :param namespace: Namespace object.
        :type namespace: str|module|dict[str, function]
        """
        if isinstance(namespace, str):
            namespace = import_module(namespace)

        if isinstance(namespace, dict):
            namespace = namespace.items()
        else:
            namespace = vars(namespace).items()

        for name, value in namespace:
            if name.startswith('_'):
                continue
            if isfunction(value) or ismethod(value):
                self.handlers[name] = value
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def check_all_models(app_configs=None, **kwargs):
    errors = []
    for model in apps.get_models():
        if app_configs is None or model._meta.app_config in app_configs:
            if not inspect.ismethod(model.check):
                errors.append(
                    Error(
                        "The '%s.check()' class method is "
                        "currently overridden by %r." % (
                            model.__name__, model.check),
                        hint=None,
                        obj=model,
                        id='models.E020'
                    )
                )
            else:
                errors.extend(model.check(**kwargs))
    return errors
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def _get_queryset_methods(cls, queryset_class):
        def create_method(name, method):
            def manager_method(self, *args, **kwargs):
                return getattr(self.get_queryset(), name)(*args, **kwargs)
            manager_method.__name__ = method.__name__
            manager_method.__doc__ = method.__doc__
            return manager_method

        new_methods = {}
        # Refs http://bugs.python.org/issue1785.
        predicate = inspect.isfunction if six.PY3 else inspect.ismethod
        for name, method in inspect.getmembers(queryset_class, predicate=predicate):
            # Only copy missing methods.
            if hasattr(cls, name):
                continue
            # Only copy public methods or methods with the attribute `queryset_only=False`.
            queryset_only = getattr(method, 'queryset_only', None)
            if queryset_only or (queryset_only is None and name.startswith('_')):
                continue
            # Copy the method onto the manager.
            new_methods[name] = create_method(name, method)
        return new_methods
项目:UPBGE-CommunityAddon    作者:elmeunick9    | 项目源码 | 文件源码
def __init__(self, Class):
        self.uniforms = []
        self.program = None
        self.error = 0

        for key, value in Class.__dict__.items() :
            if key.startswith('__'): continue
            if inspect.ismethod(getattr(Class, key)): continue
            if inspect.isfunction(getattr(Class, key)): continue

            self.__dict__[key] = value
            self.uniforms.append(key)

        if not self.owner:
            from bge import logic
            self.owner = logic.getCurrentController().owner

        self.uniforms = [x for x in self.uniforms if x not in self.owner.getPropertyNames()]
项目:UPBGE-CommunityAddon    作者:elmeunick9    | 项目源码 | 文件源码
def getAttrFromPython(path, classname):
    with open(path) as f: code = f.read()

    code = code.replace('import filter2D', '#')
    code = code.replace('from filter2D', '#')

    code = "class Filter2D: pass\n" + code

    code = compile(code, path, 'exec')
    myglob = dict()
    exec(code, dict(), myglob)

    attr = dict()
    _class = myglob[classname]
    for key, value in _class.__dict__.items():
        if key.startswith('__'): continue
        if inspect.ismethod(getattr(_class, key)): continue
        if inspect.isfunction(getattr(_class, key)): continue

        attr[key]=value

    return attr
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def check_all_models(app_configs=None, **kwargs):
    errors = []
    if app_configs is None:
        models = apps.get_models()
    else:
        models = chain.from_iterable(app_config.get_models() for app_config in app_configs)
    for model in models:
        if not inspect.ismethod(model.check):
            errors.append(
                Error(
                    "The '%s.check()' class method is currently overridden by %r."
                    % (model.__name__, model.check),
                    obj=model,
                    id='models.E020'
                )
            )
        else:
            errors.extend(model.check(**kwargs))
    return errors
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _get_xunit_setup_teardown(holder, attr_name, param_obj=None):
    """
    Return a callable to perform xunit-style setup or teardown if
    the function exists in the ``holder`` object.
    The ``param_obj`` parameter is the parameter which will be passed to the function
    when the callable is called without arguments, defaults to the ``holder`` object.
    Return ``None`` if a suitable callable is not found.
    """
    param_obj = param_obj if param_obj is not None else holder
    result = _get_xunit_func(holder, attr_name)
    if result is not None:
        arg_count = result.__code__.co_argcount
        if inspect.ismethod(result):
            arg_count -= 1
        if arg_count:
            return lambda: result(param_obj)
        else:
            return result
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def setup(self):
        """ perform setup for this test function. """
        if hasattr(self, '_preservedparent'):
            obj = self._preservedparent
        elif isinstance(self.parent, Instance):
            obj = self.parent.newinstance()
            self.obj = self._getobj()
        else:
            obj = self.parent.obj
        if inspect.ismethod(self.obj):
            setup_name = 'setup_method'
            teardown_name = 'teardown_method'
        else:
            setup_name = 'setup_function'
            teardown_name = 'teardown_function'
        setup_func_or_method = _get_xunit_setup_teardown(obj, setup_name, param_obj=self.obj)
        if setup_func_or_method is not None:
            setup_func_or_method()
        teardown_func_or_method = _get_xunit_setup_teardown(obj, teardown_name, param_obj=self.obj)
        if teardown_func_or_method is not None:
            self.addfinalizer(teardown_func_or_method)
项目:vspheretools    作者:devopshq    | 项目源码 | 文件源码
def _get_all(self):
        #If this is a MOR we need to recurse
        if self._type == 'ManagedObjectReference':
            oc = self._server._get_object_properties(self._obj, get_all=True)
            ps = oc.get_element_propSet()
            self._values = dict([(i.Name, i.Val) for i in ps])
        #Just inspect the attributes
        else:
            methods = getmembers(self._obj, predicate=inspect.ismethod)
            self._values = {}
            for name, method in methods:
                try:
                    if name.startswith("get_element_"):
                        self._values[name[12:]] = method()
                except AttributeError:
                    continue
        self._values_set = True
项目:lepo    作者:akx    | 项目源码 | 文件源码
def add_handlers(self, namespace):
        """
        Add handler functions from the given `namespace`, for instance a module.

        The namespace may be a string, in which case it is expected to be a name of a module.
        It may also be a dictionary mapping names to functions.

        Only non-underscore-prefixed functions and methods are imported.

        :param namespace: Namespace object.
        :type namespace: str|module|dict[str, function]
        """
        if isinstance(namespace, str):
            namespace = import_module(namespace)

        if isinstance(namespace, dict):
            namespace = namespace.items()
        else:
            namespace = vars(namespace).items()

        for name, value in namespace:
            if name.startswith('_'):
                continue
            if isfunction(value) or ismethod(value):
                self.handlers[name] = value
项目:auger    作者:laffra    | 项目源码 | 文件源码
def get_defining_item(self, code):
        for modname, mod in sys.modules.iteritems():
            file = getattr(mod, '__file__', '').replace('.pyc', '.py')
            if file == code.co_filename:
                for classname,clazz in inspect.getmembers(mod, predicate=inspect.isclass):
                    for name,member in inspect.getmembers(clazz, predicate=inspect.ismethod):
                        filename = member.im_func.func_code.co_filename
                        lineno = member.im_func.func_code.co_firstlineno
                        if filename == code.co_filename and lineno == code.co_firstlineno:
                            self.imports_.add((modname, clazz.__name__))
                            return clazz, member
                    for name,member in inspect.getmembers(clazz, predicate=inspect.isfunction):
                        filename = member.func_code.co_filename
                        lineno = member.func_code.co_firstlineno
                        if filename == code.co_filename and lineno == code.co_firstlineno:
                            self.imports_.add((modname, clazz.__name__))
                            return clazz, member
                self.imports_.add((modname,))
                return mod, mod
项目:cleverhans    作者:tensorflow    | 项目源码 | 文件源码
def __init__(self, docstring, class_name, class_object):
        super(NumpyClassDocString, self).__init__(docstring)
        self.class_name = class_name
        methods = dict((name, func) for name, func
                       in inspect.getmembers(class_object))

        self.has_parameters = False
        if '__init__' in methods:
            # verify if __init__ is a Python function. If it isn't
            # (e.g. the function is implemented in C), getargspec will fail
            if not inspect.ismethod(methods['__init__']):
                return
            args, varargs, keywords, defaults = inspect.getargspec(
                methods['__init__'])
            if (args and args != ['self']) or varargs or keywords or defaults:
                self.has_parameters = True
项目:weibo    作者:windskyer    | 项目源码 | 文件源码
def get_callable_name(function):
    """Generate a name from callable.

    Tries to do the best to guess fully qualified callable name.
    """
    method_self = get_method_self(function)
    if method_self is not None:
        # This is a bound method.
        if isinstance(method_self, six.class_types):
            # This is a bound class method.
            im_class = method_self
        else:
            im_class = type(method_self)
        try:
            parts = (im_class.__module__, function.__qualname__)
        except AttributeError:
            parts = (im_class.__module__, im_class.__name__, function.__name__)
    elif inspect.ismethod(function) or inspect.isfunction(function):
        # This could be a function, a static method, a unbound method...
        try:
            parts = (function.__module__, function.__qualname__)
        except AttributeError:
            if hasattr(function, 'im_class'):
                # This is a unbound method, which exists only in python 2.x
                im_class = function.im_class
                parts = (im_class.__module__,
                         im_class.__name__, function.__name__)
            else:
                parts = (function.__module__, function.__name__)
    else:
        im_class = type(function)
        if im_class is _TYPE_TYPE:
            im_class = function
        try:
            parts = (im_class.__module__, im_class.__qualname__)
        except AttributeError:
            parts = (im_class.__module__, im_class.__name__)
    return '.'.join(parts)
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def check_all_models(app_configs=None, **kwargs):
    errors = []
    if app_configs is None:
        models = apps.get_models()
    else:
        models = chain.from_iterable(app_config.get_models() for app_config in app_configs)
    for model in models:
        if not inspect.ismethod(model.check):
            errors.append(
                Error(
                    "The '%s.check()' class method is currently overridden by %r."
                    % (model.__name__, model.check),
                    obj=model,
                    id='models.E020'
                )
            )
        else:
            errors.extend(model.check(**kwargs))
    return errors
项目:third_person_im    作者:bstadie    | 项目源码 | 文件源码
def get_all_parameters(cls, parsed_args):
    prefix = _get_prefix(cls)
    if prefix is None or len(prefix) == 0:
        raise ValueError('Cannot retrieve parameters without prefix')
    info = _get_info(cls)
    if inspect.ismethod(cls.__init__):
        spec = inspect.getargspec(cls.__init__)
        if spec.defaults is None:
            arg_defaults = {}
        else:
            arg_defaults = dict(list(zip(spec.args[::-1], spec.defaults[::-1])))
    else:
        arg_defaults = {}
    all_params = {}
    for arg_name, arg_info in info.items():
        prefixed_name = prefix + arg_name
        arg_value = None
        if hasattr(parsed_args, prefixed_name):
            arg_value = getattr(parsed_args, prefixed_name)
        if arg_value is None and arg_name in arg_defaults:
            arg_value = arg_defaults[arg_name]
        if arg_value is not None:
            all_params[arg_name] = arg_value
    return all_params
项目:qcore    作者:quora    | 项目源码 | 文件源码
def getargspec(func):
    """Variation of inspect.getargspec that works for more functions.

    This function works for Cythonized, non-cpdef functions, which expose argspec information but
    are not accepted by getargspec. It also works for Python 3 functions that use annotations, which
    are simply ignored. However, keyword-only arguments are not supported.

    """
    if inspect.ismethod(func):
        func = func.__func__
    # Cythonized functions have a .__code__, but don't pass inspect.isfunction()
    try:
        code = func.__code__
    except AttributeError:
        raise TypeError('{!r} is not a Python function'.format(func))
    if hasattr(code, 'co_kwonlyargcount') and code.co_kwonlyargcount > 0:
        raise ValueError('keyword-only arguments are not supported by getargspec()')
    args, varargs, varkw = inspect.getargs(code)
    return inspect.ArgSpec(args, varargs, varkw, func.__defaults__)
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def get_instance_public_methods(instance):
    """Retrieves an objects public methods

    :param instance: The instance of the class to inspect
    :rtype: dict
    :returns: A dictionary that represents an instance's methods where
        the keys are the name of the methods and the
        values are the handler to the method.
    """
    instance_members = inspect.getmembers(instance)
    instance_methods = {}
    for name, member in instance_members:
        if not name.startswith('_'):
            if inspect.ismethod(member):
                instance_methods[name] = member
    return instance_methods
项目:django    作者:alexsukhrin    | 项目源码 | 文件源码
def check_all_models(app_configs=None, **kwargs):
    errors = []
    if app_configs is None:
        models = apps.get_models()
    else:
        models = chain.from_iterable(app_config.get_models() for app_config in app_configs)
    for model in models:
        if not inspect.ismethod(model.check):
            errors.append(
                Error(
                    "The '%s.check()' class method is currently overridden by %r."
                    % (model.__name__, model.check),
                    obj=model,
                    id='models.E020'
                )
            )
        else:
            errors.extend(model.check(**kwargs))
    return errors
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def _get_argspec(func):
    """Returns an inspect.ArgSpec instance given a function object.

    We prefer this implementation rather than the inspect module's getargspec
    since the latter has a strict check that the passed function is an instance
    of FunctionType. Cython functions do not pass this check, but they do implement
    the `func_code` and `func_defaults` attributes that we need to produce an Argspec.

    This implementation re-uses much of inspect.getargspec but removes the strict
    check allowing interface failures to be raised as AttributeError.

    See Also:
        https://github.com/python/cpython/blob/2.7/Lib/inspect.py
    """
    if inspect.ismethod(func):
        func = func.im_func

    args, varargs, varkw = inspect.getargs(func.func_code)
    return inspect.ArgSpec(args, varargs, varkw, func.func_defaults)
项目:AshsSDK    作者:thehappydinoa    | 项目源码 | 文件源码
def get_instance_public_methods(instance):
    """Retrieves an objects public methods

    :param instance: The instance of the class to inspect
    :rtype: dict
    :returns: A dictionary that represents an instance's methods where
        the keys are the name of the methods and the
        values are the handler to the method.
    """
    instance_members = inspect.getmembers(instance)
    instance_methods = {}
    for name, member in instance_members:
        if not name.startswith('_'):
            if inspect.ismethod(member):
                instance_methods[name] = member
    return instance_methods
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def __Insert(self, index, key, function, service=None):
    """Appends a hook at a certain position in the list.

    Args:
      index: the index of where to insert the function
      key: a unique key (within the module) for this particular function.
        If something from the same module with the same key is already
        registered, nothing will be added.
      function: the hook to be added.
      service: optional argument that restricts the hook to a particular api

    Returns:
      True if the collection was modified.
    """
    unique_key = (key, inspect.getmodule(function))
    if unique_key in self.__unique_keys:
      return False
    num_args = len(inspect.getargspec(function)[0])
    if (inspect.ismethod(function)):
      num_args -= 1
    self.__content.insert(index, (key, function, service, num_args))
    self.__unique_keys.add(unique_key)
    return True
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def __Insert(self, index, key, function, service=None):
    """Appends a hook at a certain position in the list.

    Args:
      index: the index of where to insert the function
      key: a unique key (within the module) for this particular function.
        If something from the same module with the same key is already
        registered, nothing will be added.
      function: the hook to be added.
      service: optional argument that restricts the hook to a particular api

    Returns:
      True if the collection was modified.
    """
    unique_key = (key, inspect.getmodule(function))
    if unique_key in self.__unique_keys:
      return False
    num_args = len(inspect.getargspec(function)[0])
    if (inspect.ismethod(function)):
      num_args -= 1
    self.__content.insert(index, (key, function, service, num_args))
    self.__unique_keys.add(unique_key)
    return True
项目:pdir2    作者:laike9m    | 项目源码 | 文件源码
def get_category(attr):
        if inspect.isclass(attr):
            return EXCEPTION if issubclass(attr, Exception) else CLASS
        elif inspect.isfunction(attr):
            return FUNCTION
        elif inspect.ismethod(attr):
            return FUNCTION
        elif inspect.isbuiltin(attr):
            return FUNCTION
        elif isinstance(attr, method_descriptor):
            # Technically, method_descriptor is descriptor, but since they
            # act as functions, let's treat them as functions.
            return FUNCTION
        elif is_descriptor(attr):
            # Maybe add getsetdescriptor memberdescriptor in the future.
            return DESCRIPTOR
        else:
            return DEFAULT_CATEGORY
项目:SimPype    作者:Mallets    | 项目源码 | 文件源码
def copy(self):
        """ Create a dopy of this simpype.Message object. 

        Returns:
            :class:`Message`

        """
        message = Message(self.sim, self.generator, self.id)
        message.generated = copy.deepcopy(self.generated)
        message.resource = self.resource
        message.location = self.location
        message.seq_num = copy.deepcopy(self.seq_num)
        message.visited = copy.copy(self.visited)
        message.is_alive = copy.deepcopy(self.is_alive)
        message.next = copy.copy(self.next)
        message.pipeline = copy.copy(self.pipeline)
        for p in self.property.values():
            message.property[p.name] = p.copy()
        for id,s in self.subscription.items():
            c = getattr(message, s.callback.__name__) if inspect.ismethod(s.callback) else s.callback
            s = message.subscribe(event = s.event, callback = c, id = id)
        return message
项目:easy-py-web-app    作者:ma-ha    | 项目源码 | 文件源码
def default(self, obj):
        if hasattr(obj, "to_json"):
            return self.default(obj.to_json())
        elif hasattr(obj, "__dict__"):
            d = dict(
                (key, value)
                for key, value in inspect.getmembers(obj)
                if not key.startswith("__")
                and not inspect.isabstract(value)
                and not inspect.isbuiltin(value)
                and not inspect.isfunction(value)
                and not inspect.isgenerator(value)
                and not inspect.isgeneratorfunction(value)
                and not inspect.ismethod(value)
                and not inspect.ismethoddescriptor(value)
                and not inspect.isroutine(value)
            )
            return self.default(d)
        return obj
项目:yowsup-zmq    作者:grandcat    | 项目源码 | 文件源码
def __init__(self):
        self.pub_commands = {}
        self.worker_thread = None

        members = inspect.getmembers(self, predicate=inspect.ismethod)
        # print(members)

        for (func_name, func_handler) in members:
            if hasattr(func_handler, '__remote_yowsup__'):
                self.pub_commands[func_name] = {
                    "fn": func_handler,
                    "args": inspect.getargspec(func_handler)[0][1:]
                }
                print(self.pub_commands[func_name])

        self.worker_thread = ZmqServer(self.pub_commands)
项目:asyncqlio    作者:SunDwarf    | 项目源码 | 文件源码
def _wrap(self, i):
    if not inspect.ismethod(i):
        return i

    # create a wrapper function
    # that hijacks any ColumnValueMixins
    def _wrapper(*args, **kwargs):
        result = i(*args, **kwargs)

        if not isinstance(result, md_operators.ColumnValueMixin):
            return result

        result.column = self
        return result

    return _wrapper
项目:rllabplusplus    作者:shaneshixiang    | 项目源码 | 文件源码
def get_all_parameters(cls, parsed_args):
    prefix = _get_prefix(cls)
    if prefix is None or len(prefix) == 0:
        raise ValueError('Cannot retrieve parameters without prefix')
    info = _get_info(cls)
    if inspect.ismethod(cls.__init__):
        spec = inspect.getargspec(cls.__init__)
        if spec.defaults is None:
            arg_defaults = {}
        else:
            arg_defaults = dict(list(zip(spec.args[::-1], spec.defaults[::-1])))
    else:
        arg_defaults = {}
    all_params = {}
    for arg_name, arg_info in info.items():
        prefixed_name = prefix + arg_name
        arg_value = None
        if hasattr(parsed_args, prefixed_name):
            arg_value = getattr(parsed_args, prefixed_name)
        if arg_value is None and arg_name in arg_defaults:
            arg_value = arg_defaults[arg_name]
        if arg_value is not None:
            all_params[arg_name] = arg_value
    return all_params
项目:mockito-python    作者:kaste    | 项目源码 | 文件源码
def get_signature(obj, method_name):
    method = getattr(obj, method_name)

    # Eat self for unbound methods bc signature doesn't do it
    if PY3:
        if (inspect.isclass(obj) and
                not inspect.ismethod(method) and
                not isinstance(
                    obj.__dict__.get(method_name),
                    staticmethod)):
            method = functools.partial(method, None)
    else:
        if (isinstance(method, types.UnboundMethodType) and
                method.__self__ is None):
            method = functools.partial(method, None)

    try:
        return signature(method)
    except:
        return None
项目:django-account-actions    作者:erudit    | 项目源码 | 文件源码
def __new__(cls, name, bases, attrs):
        super_new = super(AccountActionMetaclass, cls).__new__
        parents = [base for base in bases if isinstance(base, AccountActionMetaclass)]
        if not parents:
            # We stop here if we are considering AccountActionBase and not
            # one of its subclasses
            return super_new(cls, name, bases, attrs)
        new_action = super_new(cls, name, bases, attrs)

        # Performs some checks

        action_name = getattr(new_action, 'name', None)
        if action_name is None or not isinstance(action_name, six.string_types):
            raise ImproperlyConfigured('The "name" attribute must be a string')

        execute_method = getattr(new_action, 'execute', None)
        if execute_method is None or \
                not (inspect.ismethod(execute_method) or inspect.isfunction(execute_method)):
            raise ImproperlyConfigured('The "execute" method must be configured')

        return new_action
项目:zirc    作者:itslukej    | 项目源码 | 文件源码
def function_argument_call(func, arguments, do_thread=True):
    try:
        accepts = inspect.getargspec(func)[0]
    except TypeError:
        accepts = inspect.getargspec(func.__init__)[0]
    x = {}
    for val, arg in enumerate(accepts):
        if val == 0 and (inspect.ismethod(func) or inspect.isclass(func)):
            continue  # Ingnore first argument if it is a method
        x[arg] = arguments.get(arg)
    if do_thread:
        thread = threading.Thread(target=func, kwargs=x)
        thread.daemon = True
        return thread.start
    call_func = lambda: func(**x)
    return call_func
项目:endrebot0    作者:endreman0    | 项目源码 | 文件源码
def command(fn, name=None):
    """Decorator for functions that should be exposed as commands."""
    module = sys.modules[fn.__module__]
    if name is None:
        name = fn.__name__
    if asyncio.iscoroutinefunction(fn if inspect.isfunction(fn) else fn.__func__ if inspect.ismethod(fn) else fn.__call__): # Get the actual function for coroutine check
        @functools.wraps(fn)
        async def wrapper(*args, **kwargs):
            try:
                frame = inspect.currentframe()
                ctx = frame.f_back.f_locals['ctx']
                return await fn(ctx, *args, **kwargs)
            finally:
                del frame
    else:
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            try:
                frame = inspect.currentframe()
                ctx = frame.f_back.f_locals['ctx']
                return fn(ctx, *args, **kwargs)
            finally:
                del frame
    vars(module).setdefault('commands', {})[fn.__name__] = wrapper
    return wrapper
项目:django-schemas    作者:ryannjohnson    | 项目源码 | 文件源码
def get_class_that_defined_method(meth):
    """Returns the class that created the given method.

    A helper function for finding class methods amongst a list of many
    methods. 

    Source:
        http://stackoverflow.com/questions/3589311/get-defining-class-of-unbound-method-object-in-python-3/25959545#25959545
    """
    if inspect.ismethod(meth):
        for cls in inspect.getmro(meth.__self__.__class__):
           if cls.__dict__.get(meth.__name__) is meth:
                return cls
        meth = meth.__func__ # fallback to __qualname__ parsing
    if inspect.isfunction(meth):

        # Check to make sure the method has a "qualname"
        if not getattr(meth, '__qualname__', None):
            return None

        cls = getattr(inspect.getmodule(meth),
                      meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0])
        if isinstance(cls, type):
            return cls
    return None # not required since None would have been implicitly returned anyway
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def getargspec(obj):
    """Get the names and default values of a function's arguments.

    A tuple of four things is returned: (args, varargs, varkw, defaults).
    'args' is a list of the argument names (it may contain nested lists).
    'varargs' and 'varkw' are the names of the * and ** arguments or None.
    'defaults' is an n-tuple of the default values of the last n arguments.

    Modified version of inspect.getargspec from the Python Standard
    Library."""

    if inspect.isfunction(obj):
        func_obj = obj
    elif inspect.ismethod(obj):
        func_obj = obj.__func__
    else:
        raise TypeError('arg is not a Python function')
    args, varargs, varkw = inspect.getargs(func_obj.__code__)
    return args, varargs, varkw, func_obj.__defaults__

#-----------------------------------------------------------------------------
# Testing functions
项目:fritzchecksum    作者:mementum    | 项目源码 | 文件源码
def dobindings(self):
        members = inspect.getmembers(self.__class__, inspect.ismethod)
        for methodname, method in members:
            if hasattr(method, AutoBind.attrname):
                event = getattr(wx, method._event_name)
                boundmethod = method.__get__(self, self.__class__)
                pubname = method._event_name.lower() + '.' + self.name
                boundmethod = PubSend(pubname)(boundmethod)
                self.widget.Bind(event, boundmethod)
                # self.owner.Bind(event, boundmethod, id=self.widget.GetId())
            elif hasattr(method, AutoCallback.attrname):
                boundmethod = method.__get__(self, self.__class__)
                attr = getattr(self.__class__, method._var_name, None)
                if attr is None:
                    attr = getattr(self, method._var_name, None)
                attr.addcallback(boundmethod)
项目:fritzchecksum    作者:mementum    | 项目源码 | 文件源码
def _subscribe(self):

    def sgetter(funcname):
        def realsgetter(owner, msg):
            return owner._subs[funcname](owner, msg)
        return realsgetter

    # wx classes throw exception if getmember is applied to the instance (self)
    methods = inspect.getmembers(self.__class__, inspect.ismethod)
    topicmgr = pub.getDefaultTopicMgr()
    for mname, method in methods:
        pubsubtopic = getattr(method, '_pubrecv', None)
        if pubsubtopic:
            self._subs[mname] = method
            subsgetter = sgetter(mname)
            if (not topicmgr.getTopic(pubsubtopic, True) or
                not pub.isSubscribed(subsgetter, pubsubtopic)):

                setattr(self, mname, subsgetter)
                pub.subscribe(subsgetter.__get__(self, self.__class__),
                              pubsubtopic)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_excluding_predicates(self):
        self.istest(inspect.isbuiltin, 'sys.exit')
        if check_impl_detail():
            self.istest(inspect.isbuiltin, '[].append')
        self.istest(inspect.iscode, 'mod.spam.__code__')
        self.istest(inspect.isframe, 'tb.tb_frame')
        self.istest(inspect.isfunction, 'mod.spam')
        self.istest(inspect.isfunction, 'mod.StupidGit.abuse')
        self.istest(inspect.ismethod, 'git.argue')
        self.istest(inspect.ismodule, 'mod')
        self.istest(inspect.istraceback, 'tb')
        self.istest(inspect.isdatadescriptor, 'collections.defaultdict.default_factory')
        self.istest(inspect.isgenerator, '(x for x in range(2))')
        self.istest(inspect.isgeneratorfunction, 'generator_function_example')
        if hasattr(types, 'GetSetDescriptorType'):
            self.istest(inspect.isgetsetdescriptor,
                        'type(tb.tb_frame).f_locals')
        else:
            self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
        if hasattr(types, 'MemberDescriptorType'):
            self.istest(inspect.ismemberdescriptor,
                        'type(lambda: None).__globals__')
        else:
            self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
项目:landscape-client    作者:CanonicalLtd    | 项目源码 | 文件源码
def format_object(object):
    """
    Returns a fully-qualified name for the specified object, such as
    'landscape.lib.format.format_object()'.
    """
    if inspect.ismethod(object):
        # FIXME If the method is implemented on a base class of
        # object's class, the module name and function name will be
        # from the base class and the method's class name will be from
        # object's class.
        name = repr(object).split(" ")[2]
        return "%s.%s()" % (object.__module__, name)
    elif inspect.isfunction(object):
        name = repr(object).split(" ")[1]
        return "%s.%s()" % (object.__module__, name)
    return "%s.%s" % (object.__class__.__module__, object.__class__.__name__)
项目:py-cloud-compute-cannon    作者:Autodesk    | 项目源码 | 文件源码
def get_global_vars(func):
    """ Store any methods or variables bound from the function's closure

    Args:
        func (function): function to inspect

    Returns:
        dict: mapping of variable names to globally bound VARIABLES
    """
    closure = getclosurevars(func)
    if closure['nonlocal']:
        raise TypeError("Can't launch a job with closure variables: %s" %
                        closure['nonlocals'].keys())
    globalvars = dict(modules={},
                      functions={},
                      vars={})
    for name, value in closure['global'].items():
        if inspect.ismodule(value):  # TODO: deal FUNCTIONS from closure
            globalvars['modules'][name] = value.__name__
        elif inspect.isfunction(value) or inspect.ismethod(value):
            globalvars['functions'][name] = value
        else:
            globalvars['vars'][name] = value

    return globalvars