本文整理匯總了Python中inspect.isgeneratorfunction方法的典型用法代碼示例。如果您正苦於以下問題:Python inspect.isgeneratorfunction方法的具體用法?Python inspect.isgeneratorfunction怎麽用?Python inspect.isgeneratorfunction使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類inspect
的用法示例。
在下文中一共展示了inspect.isgeneratorfunction方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_excluding_predicates
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def test_excluding_predicates(self):
self.istest(inspect.isbuiltin, 'sys.exit')
self.istest(inspect.isbuiltin, '[].append')
self.istest(inspect.iscode, 'mod.spam.func_code')
self.istest(inspect.isframe, 'tb.tb_frame')
self.istest(inspect.isfunction, 'mod.spam')
self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
self.istest(inspect.ismethod, 'git.argue')
self.istest(inspect.ismodule, 'mod')
self.istest(inspect.istraceback, 'tb')
self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
self.istest(inspect.isgenerator, '(x for x in xrange(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, 'datetime.timedelta.days')
else:
self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
示例2: pytest_fixture
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def pytest_fixture(hook=None, name=None, **kwargs):
"""Generator-aware pytest.fixture decorator for legacy pytest versions"""
def _decorate(f):
if name is not None:
# 'name' argument is not supported in this old version, use the __name__ trick.
f.__name__ = name
# call hook if needed
if hook is not None:
f = hook(f)
# create the fixture
if isgeneratorfunction(f):
return pytest.yield_fixture(**kwargs)(f)
else:
return pytest.fixture(**kwargs)(f)
return _decorate
示例3: test_iscoroutine
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def test_iscoroutine(self):
gen_coro = gen_coroutine_function_example(1)
coro = coroutine_function_example(1)
self.assertFalse(
inspect.iscoroutinefunction(gen_coroutine_function_example))
self.assertFalse(inspect.iscoroutine(gen_coro))
self.assertTrue(
inspect.isgeneratorfunction(gen_coroutine_function_example))
self.assertTrue(inspect.isgenerator(gen_coro))
self.assertTrue(
inspect.iscoroutinefunction(coroutine_function_example))
self.assertTrue(inspect.iscoroutine(coro))
self.assertFalse(
inspect.isgeneratorfunction(coroutine_function_example))
self.assertFalse(inspect.isgenerator(coro))
coro.close(); gen_coro.close() # silence warnings
示例4: __init__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def __init__(
self,
func: Callable,
*args,
SignalsClass: Type[QObject] = GeneratorWorkerSignals,
**kwargs,
):
if not inspect.isgeneratorfunction(func):
raise TypeError(
f"Regular function {func} cannot be used with "
"GeneratorWorker, use FunctionWorker instead"
)
super().__init__(SignalsClass=SignalsClass)
self._gen = func(*args, **kwargs)
self._incoming_value = None
self._pause_requested = False
self._resume_requested = False
self._paused = False
# polling interval: ONLY relevant if the user paused a running worker
self._pause_interval = 0.01
示例5: _imp
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def _imp(cls, loaded):
"""
Returns the operation implemention from a loaded entrypoint object, or
None if its not an operation implemention or doesn't have the imp
parameter which is an operation implemention.
"""
for obj in [getattr(loaded, "imp", None), loaded]:
if inspect.isclass(obj) and issubclass(obj, cls):
return obj
if (
inspect.isfunction(loaded)
or inspect.isgeneratorfunction(loaded)
or inspect.iscoroutinefunction(loaded)
or inspect.isasyncgenfunction(loaded)
):
return op(loaded).imp
return None
示例6: fn_time
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def fn_time(func, desc=None):
@contextmanager
def timing(*a, **kw):
start = time.time()
try:
yield
finally:
d = desc if desc else fn_desc(func, *a, **kw)
log.debug('%s: done for %.2fs', d, time.time() - start)
def inner_fn(*a, **kw):
with timing(*a, **kw):
return func(*a, **kw)
def inner_gen(*a, **kw):
with timing(*a, **kw):
yield from func(*a, **kw)
inner = inner_gen if inspect.isgeneratorfunction(func) else inner_fn
return ft.wraps(func)(inner)
示例7: default
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat() + 'Z'
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
示例8: isgeneratorfunction
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def isgeneratorfunction(caller):
return False
示例9: decorate
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def decorate(func, caller, extras=()):
"""
decorate(func, caller) decorates a function using a caller.
If the caller is a generator function, the resulting function
will be a generator function.
"""
evaldict = dict(_call_=caller, _func_=func)
es = ''
for i, extra in enumerate(extras):
ex = '_e%d_' % i
evaldict[ex] = extra
es += ex + ', '
if '3.5' <= sys.version < '3.6':
# with Python 3.5 isgeneratorfunction returns True for all coroutines
# however we know that it is NOT possible to have a generator
# coroutine in python 3.5: PEP525 was not there yet
generatorcaller = isgeneratorfunction(
caller) and not iscoroutinefunction(caller)
else:
generatorcaller = isgeneratorfunction(caller)
if generatorcaller:
fun = FunctionMaker.create(
func, "for res in _call_(_func_, %s%%(shortsignature)s):\n"
" yield res" % es, evaldict, __wrapped__=func)
else:
fun = FunctionMaker.create(
func, "return _call_(_func_, %s%%(shortsignature)s)" % es,
evaldict, __wrapped__=func)
if hasattr(func, '__qualname__'):
fun.__qualname__ = func.__qualname__
return fun
示例10: test_functions_are_generators
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def test_functions_are_generators(func2test, method_param, base_class, expected):
from inspect import isgenerator, isgeneratorfunction
func_obj = _load_obj(func_name=func2test)
generator_obj = func_obj(method_param, base_class)
assert isgeneratorfunction(func_obj) is expected
assert isgenerator(generator_obj) is expected
示例11: echo_via_pager
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def echo_via_pager(text_or_generator, color=None):
"""This function takes a text and shows it via an environment specific
pager on stdout.
.. versionchanged:: 3.0
Added the `color` flag.
:param text_or_generator: the text to page, or alternatively, a
generator emitting the text to page.
:param color: controls if the pager supports ANSI colors or not. The
default is autodetection.
"""
color = resolve_color_default(color)
if inspect.isgeneratorfunction(text_or_generator):
i = text_or_generator()
elif isinstance(text_or_generator, string_types):
i = [text_or_generator]
else:
i = iter(text_or_generator)
# convert every element of i to a text type if necessary
text_generator = (el if isinstance(el, string_types) else text_type(el)
for el in i)
from ._termui_impl import pager
return pager(itertools.chain(text_generator, "\n"), color)
示例12: read_session
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def read_session(function):
'''
decorator that set the session variable to use inside a function.
With that decorator it's possible to use the session variable like if a global variable session is declared.
session is a sqlalchemy session, and you can get one calling get_session().
This is useful if only SELECTs and the like are being done; anything involving
INSERTs, UPDATEs etc should use transactional_session.
'''
@retry(retry_on_exception=retry_if_db_connection_error,
wait_fixed=500,
stop_max_attempt_number=2,
wrap_exception=False)
@wraps(function)
def new_funct(*args, **kwargs):
if isgeneratorfunction(function):
raise RucioException('read_session decorator should not be used with generator. Use stream_session instead.')
if not kwargs.get('session'):
session = get_session()
try:
kwargs['session'] = session
return function(*args, **kwargs)
except TimeoutError as error:
session.rollback() # pylint: disable=maybe-no-member
raise DatabaseException(str(error))
except DatabaseError as error:
session.rollback() # pylint: disable=maybe-no-member
raise DatabaseException(str(error))
except:
session.rollback() # pylint: disable=maybe-no-member
raise
finally:
session.remove()
try:
return function(*args, **kwargs)
except:
raise
new_funct.__doc__ = function.__doc__
return new_funct
示例13: is_generator
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def is_generator(obj):
import inspect
return obj is not None and (inspect.isgeneratorfunction(obj) or inspect.isgenerator(obj) or hasattr(obj, 'next') or hasattr(obj, '__next__'))
示例14: is_generator
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def is_generator(func):
genfunc = inspect.isgeneratorfunction(func)
return genfunc and not iscoroutinefunction(func)
示例15: istest
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isgeneratorfunction [as 別名]
def istest(self, predicate, exp):
obj = eval(exp)
self.assertTrue(predicate(obj), '%s(%s)' % (predicate.__name__, exp))
for other in self.predicates - set([predicate]):
if predicate == inspect.isgeneratorfunction and\
other == inspect.isfunction:
continue
self.assertFalse(other(obj), 'not %s(%s)' % (other.__name__, exp))