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


Python types.GeneratorType方法代码示例

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


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

示例1: is_iterator

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [as 别名]
def is_iterator(obj):
    """Detect if the object provided implements the iterator protocol.

    (i.e. like a generator).

    This will return False for objects which are iterable,
    but not iterators themselves.
    """
    from types import GeneratorType
    if isinstance(obj, GeneratorType):
        return True
    elif not hasattr(obj, '__iter__'):
        return False
    else:
        # Types which implement the protocol must return themselves when
        # invoking 'iter' upon them.
        return iter(obj) is obj 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:19,代码来源:__init__.py

示例2: default

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [as 别名]
def default(self, obj):
        from certidude.user import User
        if isinstance(obj, ipaddress._IPAddressBase):
            return str(obj)
        if isinstance(obj, set):
            return tuple(obj)
        if isinstance(obj, datetime):
            return obj.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
        if isinstance(obj, date):
            return obj.strftime("%Y-%m-%d")
        if isinstance(obj, timedelta):
            return obj.total_seconds()
        if isinstance(obj, types.GeneratorType):
            return tuple(obj)
        if isinstance(obj, User):
            return dict(name=obj.name, given_name=obj.given_name,
                surname=obj.surname, mail=obj.mail)
        return json.JSONEncoder.default(self, obj) 
开发者ID:laurivosandi,项目名称:certidude,代码行数:20,代码来源:decorators.py

示例3: isgenerator

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [as 别名]
def isgenerator(object):
    """Return true if the object is a generator.

    Generator objects provide these attributes:
        __iter__        defined to support iteration over container
        close           raises a new GeneratorExit exception inside the
                        generator to terminate the iteration
        gi_code         code object
        gi_frame        frame object or possibly None once the generator has
                        been exhausted
        gi_running      set to 1 when generator is executing, 0 otherwise
        next            return the next item from the container
        send            resumes the generator and "sends" a value that becomes
                        the result of the current yield-expression
        throw           used to raise an exception inside the generator"""
    return isinstance(object, types.GeneratorType) 
开发者ID:war-and-code,项目名称:jawfish,代码行数:18,代码来源:inspect.py

示例4: ensure_fanart

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [as 别名]
def ensure_fanart(fn):
    """Makes sure that if the listitem doesn't have a fanart, we properly set one."""
    from functools import wraps
    @wraps(fn)
    def _fn(*a, **kwds):
        import os
        import types
        from kmediatorrent import plugin
        items = fn(*a, **kwds)
        if items is None:
            return
        if isinstance(items, types.GeneratorType):
            items = list(items)
        for item in items:
            properties = item.setdefault("properties", {})
            if not properties.get("fanart_image"):
                properties["fanart_image"] = plugin.addon.getAddonInfo("fanart")
        return items
    return _fn 
开发者ID:jmarth,项目名称:plugin.video.kmediatorrent,代码行数:21,代码来源:utils.py

示例5: cached_route

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [as 别名]
def cached_route(*args, **kwargs):
    from functools import wraps
    def cached(fn):
        @wraps(fn)
        def _fn(*a, **kwds):
            import hashlib
            basename = "kmediatorrent.route.%s" % hashlib.sha1(plugin.request.path).hexdigest()
            with shelf(basename, ttl=kwargs.get("ttl") or 0) as result:
                if not result.get("value"):
                    ret = fn(*a, **kwds)
                    import types
                    if isinstance(ret, types.GeneratorType):
                        ret = list(ret)
                    result["value"] = ret
                if kwargs.get("content_type"):
                    plugin.set_content(kwargs.get("content_type"))
                return result["value"]
        return _fn
    if len(args) == 1 and callable(args[0]):
        return cached(args[0])
    return cached 
开发者ID:jmarth,项目名称:plugin.video.kmediatorrent,代码行数:23,代码来源:caching.py

示例6: is_generator

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [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

示例7: test_reading1

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [as 别名]
def test_reading1():

    # Calling returns a generator
    gen = imageio_ffmpeg.read_frames(test_file1)
    assert isinstance(gen, types.GeneratorType)

    # First yield is a meta dict
    meta = gen.__next__()
    assert isinstance(meta, dict)
    for key in ("size", "fps", "duration"):
        assert key in meta

    # Read frames
    framesize = meta["size"][0] * meta["size"][1] * 3
    assert framesize == 1280 * 720 * 3
    count = 0
    for frame in gen:
        assert isinstance(frame, bytes) and len(frame) == framesize
        count += 1

    assert count == 280 
开发者ID:imageio,项目名称:imageio-ffmpeg,代码行数:23,代码来源:test_io.py

示例8: test_batch

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [as 别名]
def test_batch():
    """Test the batch feed dict generator."""
    X = np.arange(100)
    fd = {'X': X}

    data = ab.batch(fd, batch_size=10, n_iter=10)

    # Make sure this is a generator
    assert isinstance(data, GeneratorType)

    # Make sure we get a dict back of a length we expect
    d = next(data)
    assert isinstance(d, dict)
    assert 'X' in d
    assert len(d['X']) == 10

    # Test we get all of X back in one sweep of the data
    accum = list(d['X'])
    for ds in data:
        assert len(ds['X']) == 10
        accum.extend(list(ds['X']))

    assert len(accum) == len(X)
    assert set(X) == set(accum) 
开发者ID:gradientinstitute,项目名称:aboleth,代码行数:26,代码来源:test_utils.py

示例9: test_batch_predict

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [as 别名]
def test_batch_predict():
    """Test the batch prediction feed dict generator."""
    X = np.arange(100)
    fd = {'X': X}

    data = ab.batch_prediction(fd, batch_size=10)

    # Make sure this is a generator
    assert isinstance(data, GeneratorType)

    # Make sure we get a dict back of a length we expect with correct indices
    for ind, d in data:
        assert isinstance(d, dict)
        assert 'X' in d
        assert len(d['X']) == 10
        assert all(X[ind] == d['X']) 
开发者ID:gradientinstitute,项目名称:aboleth,代码行数:18,代码来源:test_utils.py

示例10: read_tag

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [as 别名]
def read_tag(self, *tags):
        """ read tag from a connected plc

        Possible combination can be passed to this method:
                - ('Counts') a single tag name
                - (['ControlWord']) a list with one tag or many
                - (['parts', 'ControlWord', 'Counts'])

        At the moment there is not a strong validation for the argument passed. The user should verify
        the correctness of the format passed.

        :return: None is returned in case of error otherwise the tag list is returned
        """

        if not self._forward_open():
            self.__log.warning("Target did not connected. read_tag will not be executed.")
            raise DataError("Target did not connected. read_tag will not be executed.")

        if len(tags) == 1:
            if isinstance(tags[0], (list, tuple, GeneratorType)):
                return self._read_tag_multi(tags[0])
            else:
                return self._read_tag_single(tags[0])
        else:
            return self._read_tag_multi(tags) 
开发者ID:ottowayi,项目名称:pycomm3,代码行数:27,代码来源:clx_legacy.py

示例11: isgenerator

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [as 别名]
def isgenerator(object):
    """Return true if the object is a generator.

    Generator objects provide these attributes:
        __iter__        defined to support interation over container
        close           raises a new GeneratorExit exception inside the
                        generator to terminate the iteration
        gi_code         code object
        gi_frame        frame object or possibly None once the generator has
                        been exhausted
        gi_running      set to 1 when generator is executing, 0 otherwise
        next            return the next item from the container
        send            resumes the generator and "sends" a value that becomes
                        the result of the current yield-expression
        throw           used to raise an exception inside the generator"""
    return isinstance(object, types.GeneratorType) 
开发者ID:glmcdona,项目名称:meddle,代码行数:18,代码来源:inspect.py

示例12: _wrap_task_call

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [as 别名]
def _wrap_task_call(func):
    # type: (F) -> F
    """
    Wrap task call with a try catch to get exceptions.
    Pass the client on to raise_exception so it can get rebinded.
    """
    client = Hub.current.client

    @wraps(func)
    def _inner(*args, **kwargs):
        # type: (*Any, **Any) -> Any
        try:
            gen = func(*args, **kwargs)
        except Exception:
            raise_exception(client)

        if not isinstance(gen, types.GeneratorType):
            return gen
        return _wrap_generator_call(gen, client)

    setattr(_inner, USED_FUNC, True)
    return _inner  # type: ignore 
开发者ID:getsentry,项目名称:sentry-python,代码行数:24,代码来源:beam.py

示例13: unroll_generators

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [as 别名]
def unroll_generators(generator):
    '''
    Take a generator and unroll any sub-generators recursively. This is
    essentially a Python 2 way of doing `yield from` in Python 3 (given
    iterating the entire thing).
    '''

    # Ensure we have a generator (prevents ccommands returning lists)
    if not isinstance(generator, GeneratorType):
        raise TypeError('{0} is not a generator'.format(generator))

    items = []

    for item in generator:
        if isinstance(item, GeneratorType):
            items.extend(unroll_generators(item))
        else:
            items.append(item)

    return items 
开发者ID:Fizzadar,项目名称:pyinfra,代码行数:22,代码来源:util.py

示例14: _is_inventory_group

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [as 别名]
def _is_inventory_group(key, value):
    '''
    Verify that a module-level variable (key = value) is a valid inventory group.
    '''

    if (
        key.startswith('_')
        or not isinstance(value, (list, tuple, GeneratorType))
    ):
        return False

    # If the group is a tuple of (hosts, data), check the hosts
    if isinstance(value, tuple):
        value = value[0]

    # Expand any generators of hosts
    if isinstance(value, GeneratorType):
        value = list(value)

    return all(
        isinstance(item, ALLOWED_HOST_TYPES)
        for item in value
    ) 
开发者ID:Fizzadar,项目名称:pyinfra,代码行数:25,代码来源:inventory.py

示例15: _find_generators

# 需要导入模块: import types [as 别名]
# 或者: from types import GeneratorType [as 别名]
def _find_generators(self, item):
        """ A recursive function to flatten generators into lists """
        try:
            result = []
            # Make sure dicts aren't flattened to lists
            if isinstance(item, dict):
                result = {}
                for i in item:
                    result[self._find_generators(i)] = self._find_generators(item[i])
                return result

            # Since NoneObjects and strings are both iterable, treat them specially
            if isinstance(item, obj.NoneObject) or isinstance(item, str):
                return item

            if isinstance(item, types.GeneratorType):
                raise CacheContainsGenerator
            for x in iter(item):
                flat_x = self._find_generators(x)
                result.append(flat_x)

            return result
        except TypeError:
            return item 
开发者ID:virtualrealitysystems,项目名称:aumfor,代码行数:26,代码来源:cache.py


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