python类isfunction()的实例源码

__init__.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def add(self, categorize):
        """Add given method to categorize messages. When a message is received,
        each of the added methods (most recently added method first) is called
        with the message. The method should return a category (any hashable
        object) or None (in which case next recently added method is called with
        the same message). If all the methods return None for a given message,
        the message is queued with category=None, so that 'receive' method here
        works just as Task.receive.
        """
        if inspect.isfunction(categorize):
            argspec = inspect.getargspec(categorize)
            if len(argspec.args) != 1:
                categorize = None
        elif type(categorize) != partial_func:
            categorize = None

        if categorize:
            self._categorize.insert(0, categorize)
        else:
            logger.warning('invalid categorize function ignored')
__init__.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def add(self, categorize):
        """Add given method to categorize messages. When a message is received,
        each of the added methods (most recently added method first) is called
        with the message. The method should return a category (any hashable
        object) or None (in which case next recently added method is called with
        the same message). If all the methods return None for a given message,
        the message is queued with category=None, so that 'receive' method here
        works just as Task.receive.
        """
        if inspect.isfunction(categorize):
            argspec = inspect.getargspec(categorize)
            if len(argspec.args) != 1:
                categorize = None
        elif type(categorize) != partial_func:
            categorize = None

        if categorize:
            self._categorize.insert(0, categorize)
        else:
            logger.warning('invalid categorize function ignored')
doctest.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function")
__init__.py 文件源码 项目:chaps 作者: ekiro 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def inject(*args):
    if len(args) == 1 and inspect.isfunction(args[0]):
        return inject_function(args[0])
    else:
        def inject_class(cls):
            orig_init = cls.__init__

            def __init__(self, *a, **kw):
                container = Container()
                for arg in args:
                    obj = container.get_object(arg)
                    setattr(self, arg, obj)
                orig_init(self, *a, **kw)

            cls.__init__ = __init__

            return cls

        return inject_class
WidgetGroup.py 文件源码 项目:NeoAnalysis 作者: neoanalysis 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
WidgetGroup.py 文件源码 项目:NeoAnalysis 作者: neoanalysis 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
langhelpers.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
doctest.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is func_globals(object)
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function")
recipe-553262.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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()
pep8.py 文件源码 项目:SoCFoundationFlow 作者: mattaw 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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)
layerparams.py 文件源码 项目:deep-prior 作者: moberweger 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def activation_str(self):
        """
        Get printable string from activation function.
        :return: string
        """
        if hasattr(self, 'activation'):
            if self.activation is None:
                return str(None)
            elif inspect.isclass(self.activation):
                return self.activation.__class__.__name__
            elif inspect.isfunction(self.activation):
                return self.activation.__name__
            else:
                return str(self.activation)
        else:
            return ''
router.py 文件源码 项目:ml-rest 作者: apinf 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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
extensions.py 文件源码 项目:veneer-py 作者: flowmatters 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def add_network_methods(target):
    '''
    Attach extension methods to an object that represents a Veneer network.
    Note: The 'network_' prefix will be removed from method names.

    target: Veneer network object to attach extension methods to.
    '''
    import veneer.extensions as extensions # Import self to inspect available functions

    # Generate dict of {function name: function}, skipping this function
    this_func_name = sys._getframe().f_code.co_name
    funcs = inspect.getmembers(extensions, inspect.isfunction)
    funcs = dict((func_name, func) for func_name, func in funcs
                  if func_name != this_func_name
            )

    # Assign functions to target, removing the 'network_' prefix
    for f_name, f in funcs.items():
        if f_name.startswith('network_'):
            f_name = f_name.replace('network_', '')
        setattr(target, f_name, MethodType(f, target))
manager.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
edit.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def __new__(cls, name, bases, attrs):
        get_form = attrs.get('get_form')
        if get_form and inspect.isfunction(get_form):
            try:
                inspect.getcallargs(get_form, None)
            except TypeError:
                warnings.warn(
                    "`%s.%s.get_form` method must define a default value for "
                    "its `form_class` argument." % (attrs['__module__'], name),
                    RemovedInDjango110Warning, stacklevel=2
                )

                def get_form_with_form_class(self, form_class=None):
                    if form_class is None:
                        form_class = self.get_form_class()
                    return get_form(self, form_class=form_class)
                attrs['get_form'] = get_form_with_form_class
        return super(FormMixinBase, cls).__new__(cls, name, bases, attrs)
Fake.py 文件源码 项目:UPBGE-CommunityAddon 作者: elmeunick9 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
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()]
UIshader.py 文件源码 项目:UPBGE-CommunityAddon 作者: elmeunick9 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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
loader.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def getTestCaseNames(self, testCaseClass):
        """Override to select with selector, unless
        config.getTestCaseNamesCompat is True
        """
        if self.config.getTestCaseNamesCompat:
            return unittest.TestLoader.getTestCaseNames(self, testCaseClass)

        def wanted(attr, cls=testCaseClass, sel=self.selector):
            item = getattr(cls, attr, None)
            if isfunction(item):
                item = unbound_method(cls, item)
            elif not ismethod(item):
                return False
            return sel.wantMethod(item)

        cases = filter(wanted, dir(testCaseClass))

        # add runTest if nothing else picked
        if not cases and hasattr(testCaseClass, 'runTest'):
            cases = ['runTest']
        if self.sortTestMethodsUsing:
            sort_list(cases, cmp_to_key(self.sortTestMethodsUsing))
        return cases
loader.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def loadTestsFromTestClass(self, cls):
        """Load tests from a test class that is *not* a unittest.TestCase
        subclass.

        In this case, we can't depend on the class's `__init__` taking method
        name arguments, so we have to compose a MethodTestCase for each
        method in the class that looks testlike.
        """
        def wanted(attr, cls=cls, sel=self.selector):
            item = getattr(cls, attr, None)
            if isfunction(item):
                item = unbound_method(cls, item)
            elif not ismethod(item):
                return False
            return sel.wantMethod(item)
        cases = [self.makeTest(getattr(cls, case), cls)
                 for case in filter(wanted, dir(cls))]
        for test in self.config.plugins.loadTestsFromTestClass(cls):
            cases.append(test)
        return self.suiteClass(ContextList(cases, context=cls))
dtcompat.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            # Some jython classes don't set __module__
            return module.__name__ == getattr(object, '__module__', None)
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function")
doctest.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function")
router.py 文件源码 项目:lepo 作者: akx 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
default.py 文件源码 项目:auger 作者: laffra 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
events.py 文件源码 项目:annotated-py-asyncio 作者: hhstore 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def _get_function_source(func):
    if _PY34:
        func = inspect.unwrap(func)
    elif hasattr(func, '__wrapped__'):
        func = func.__wrapped__

    if inspect.isfunction(func):
        code = func.__code__
        return (code.co_filename, code.co_firstlineno)

    if isinstance(func, functools.partial):
        return _get_function_source(func.func)

    if _PY34 and isinstance(func, functools.partialmethod):
        return _get_function_source(func.func)
    return None
langhelpers.py 文件源码 项目:QXSConsolas 作者: qxsch 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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)
quickcache_helper.py 文件源码 项目:quickcache 作者: dimagi 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def get_cache_key(self, *args, **kwargs):
        callargs = inspect.getcallargs(self.fn, *args, **kwargs)
        values = []
        if isfunction(self.vary_on):
            values = self.vary_on(*args, **kwargs)
        else:
            for arg_name, attrs in self.vary_on:
                value = callargs[arg_name]
                for attr in attrs:
                    value = getattr(value, attr)
                values.append(value)
        args_string = ','.join(self._serialize_for_key(value)
                               for value in values)
        if len(args_string) > 150:
            args_string = 'H' + self._hash(args_string)
        return 'quickcache.{}/{}'.format(self.prefix, args_string)
reflection.py 文件源码 项目:weibo 作者: windskyer 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
loadables.py 文件源码 项目:zun 作者: openstack 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
python_filter_generator.py 文件源码 项目:ParaViewGeophysics 作者: banesullivan 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def replaceFunctionWithSourceString(namespace, functionName, allowEmpty=False):

    func = namespace.get(functionName)
    if not func:
        if allowEmpty:
            namespace[functionName] = ''
            return
        else:
            raise Exception('Function %s not found in input source code.' % functionName)

    if not inspect.isfunction(func):
        raise Exception('Object %s is not a function object.' % functionName)

    lines = inspect.getsourcelines(func)[0]

    if len(lines) <= 1:
        raise Exception('Function %s must not be a single line of code.' % functionName)

    # skip first line (the declaration) and then dedent the source code
    sourceCode = textwrap.dedent(''.join(lines[1:]))

    namespace[functionName] = sourceCode
testing.py 文件源码 项目:qcore 作者: quora 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def decorate_func_or_method_or_class(decorator):
    """Applies a decorator to a function, method, or all methods of a class.

    This is a decorator that is applied to a decorator to allow a
    function/method decorator to be applied to a class and have it act on all
    test methods of the class.

    """
    def decorate(func_or_class):
        if inspect.isclass(func_or_class):
            return decorate_all_test_methods(decorator)(func_or_class)
        elif inspect.isfunction(func_or_class):
            return decorator(func_or_class)
        else:
            assert False, 'Target of decorator must be function or class'
    return decorate


问题


面经


文章

微信
公众号

扫码关注公众号