本文整理匯總了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
示例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)
示例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)
示例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
示例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
示例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))
示例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
示例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)
示例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'])
示例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)
示例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)
示例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
示例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
示例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
)
示例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