本文整理汇总了Python中inspect.getmembers方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.getmembers方法的具体用法?Python inspect.getmembers怎么用?Python inspect.getmembers使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.getmembers方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
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
示例2: handle_class
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
def handle_class(val, class_name):
cls_errors = []
docstring = inspect.getdoc(val)
if docstring is None:
cls_errors.append((class_name,
'**missing** class-level docstring'))
else:
cls_errors = [
(e,) for e in
NumpyClassDocString(docstring, class_name, val).get_errors()
]
# Get public methods and parse their docstrings
methods = dict(((name, func) for name, func in inspect.getmembers(val)
if not name.startswith('_') and callable(func) and
type(func) is not type))
for m_name, method in six.iteritems(methods):
# skip error check if the method was inherited
# from a parent class (which means it wasn't
# defined in this source file)
if inspect.getmodule(method) is not None:
continue
cls_errors.extend(handle_method(method, m_name, class_name))
return cls_errors
示例3: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
def __init__(self, log=True):
global isLog
isLog = log
self._name = self.__class__.__name__
self._routes = {
n: v
for n, v in inspect.getmembers(self, inspect.ismethod)
if not v.__func__.__qualname__.startswith(("Base.", "Window.", "Server."))
}
self._routes.update(
dict(set=self.set, get=self.get)
) # add get/set config methods
if "init" in self._routes:
del self._routes[
"init"
] # ensure that a server-side init() is not exposed on client-side
self._clients = []
示例4: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
def __init__(cls, name, bases, d):
# Prepare
methods = set(cls.methods or [])
methods_map = defaultdict(dict)
# Methods
for view_name, func in inspect.getmembers(cls):
# Collect methods decorated with methodview()
info = _MethodViewInfo.get_info(func)
if info is not None:
# @methodview-decorated view
for method in info.methods:
methods_map[method][view_name] = info
methods.add(method)
# Finish
cls.methods = tuple(sorted(methods_map.keys())) # ('GET', ... )
cls.methods_map = dict(methods_map) # { 'GET': {'get': _MethodViewInfo } }
super(MethodViewType, cls).__init__(name, bases, d)
示例5: describe_template_sets
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
def describe_template_sets():
"""
Print the available template sets in this demo, with a short description"
"""
import inspect
import sys
# a bit of magic to get all functions in this module
templatesets = inspect.getmembers(sys.modules[__name__], inspect.isfunction)
for (name, obj) in templatesets:
if name == "describe_template_sets":
continue
print(name, obj.__doc__, "\n")
######################################################################
# The Brill Tagger
######################################################################
示例6: _read_options
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
def _read_options(mcs, name, bases, attrs, options_members):
"""
Parses model `Options` class into a `SchemaOptions` instance.
"""
options_class = attrs.get('__optionsclass__', schema.SchemaOptions)
if 'Options' in attrs:
for key, value in inspect.getmembers(attrs['Options']):
if key.startswith("__"):
continue
elif key.startswith("_"):
extras = options_members.get("extras", {}).copy()
extras.update({key: value})
options_members["extras"] = extras
elif key == "roles":
roles = options_members.get("roles", {}).copy()
roles.update(value)
options_members[key] = roles
else:
options_members[key] = value
return options_class(**options_members)
示例7: collect_options
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
def collect_options(mcs, bases, attrs):
"""
Collects options from the current class and its parent classes.
:returns: a dictionary of options
"""
options = {}
# options from parent classes:
for base in reversed(bases):
if hasattr(base, '_options'):
for key, value in inspect.getmembers(base._options):
if not key.startswith('_') and value is not None:
options[key] = value
# options from the current class:
if 'Options' in attrs:
for key, value in inspect.getmembers(attrs['Options']):
if not key.startswith('_') and value is not None:
# HACK HACK HACK
if inspect.ismethod(value) and value.im_self is None:
value = value.im_func
options[key] = value
return options
示例8: _get_oauth_scopes
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
def _get_oauth_scopes(modules=_API_CLIENT_MODULES):
"""Retrieves all OAuth2 Scopes required for management.
Args:
modules: Sequence[module], a sequence of modules to extract OAuth2 scopes
from.
Returns:
A list of all of the OAuth2 Scopes required for management.
"""
scopes = []
for client in modules:
for name, cls in inspect.getmembers(client, inspect.isclass):
if name.endswith('API') and hasattr(cls, 'SCOPES'):
scopes.extend(cls.SCOPES)
return sorted(list(set(scopes)))
示例9: test_all_endpoints_have_scope_attributes
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
def test_all_endpoints_have_scope_attributes(self, client):
# Skip paging calls and options
skips = {
'next',
'previous',
'all_pages',
'all_items',
'chunked',
'max_limits',
'token_as',
}
for name, method in getmembers(client, predicate=ismethod):
if name.startswith('_') or name in skips:
continue
assert isinstance(method.scope, Scope)
assert isinstance(method.required_scope, Scope)
assert isinstance(method.optional_scope, Scope)
assert method.scope == method.required_scope + method.optional_scope
示例10: get_client_method_names
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
def get_client_method_names() -> List[str]:
"""Extracts method names from LookerClient to test for bad responses"""
client_members: List[Tuple[str, Callable]] = inspect.getmembers(
LookerClient, predicate=inspect.isroutine
)
client_methods: List[str] = [
member[0] for member in client_members if not member[0].startswith("__")
]
for skip_method in (
"authenticate",
"cancel_query_task",
"request",
"get",
"post",
"put",
"patch",
"delete",
):
client_methods.remove(skip_method)
return client_methods
示例11: test_section_configuration_matches_type_specification
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
def test_section_configuration_matches_type_specification(self):
""""The section annotations should match the actual types of the sections."""
sections = (
cls
for (name, cls) in inspect.getmembers(constants)
if hasattr(cls, 'section') and isinstance(cls, type)
)
for section in sections:
for name, annotation in section.__annotations__.items():
with self.subTest(section=section.__name__, name=name, annotation=annotation):
value = getattr(section, name)
origin = typing.get_origin(annotation)
annotation_args = typing.get_args(annotation)
failure_msg = f"{value} is not an instance of {annotation}"
if origin is typing.Union:
is_instance = is_any_instance(value, annotation_args)
self.assertTrue(is_instance, failure_msg)
else:
is_instance = is_annotation_instance(value, annotation)
self.assertTrue(is_instance, failure_msg)
示例12: _generate_state_machine
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
def _generate_state_machine(rules_object: type) -> type:
bases = (_BrownieStateMachine, rules_object, sf.RuleBasedStateMachine)
machine = type("BrownieStateMachine", bases, {})
strategies = {k: v for k, v in getmembers(rules_object) if isinstance(v, SearchStrategy)}
for attr, fn in filter(_member_filter, getmembers(machine)):
varnames = [[i] for i in fn.__code__.co_varnames[1 : fn.__code__.co_argcount]]
if fn.__defaults__:
for i in range(-1, -1 - len(fn.__defaults__), -1):
varnames[i].append(fn.__defaults__[i])
if _attr_filter(attr, "initialize"):
wrapped = sf.initialize(**{key[0]: strategies[key[-1]] for key in varnames})
setattr(machine, attr, wrapped(fn))
elif _attr_filter(attr, "invariant"):
setattr(machine, attr, sf.invariant()(fn))
elif _attr_filter(attr, "rule"):
wrapped = sf.rule(**{key[0]: strategies[key[-1]] for key in varnames})
setattr(machine, attr, wrapped(fn))
return machine
示例13: main
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
def main():
args = make_args()
config = configparser.ConfigParser()
utils.load_config(config, args.config)
for cmd in args.modify:
utils.modify_config(config, cmd)
with open(os.path.expanduser(os.path.expandvars(args.logging)), 'r') as f:
logging.config.dictConfig(yaml.load(f))
model_dir = utils.get_model_dir(config)
path, step, epoch = utils.train.load_model(model_dir)
state_dict = torch.load(path, map_location=lambda storage, loc: storage)
mapper = [(inflection.underscore(name), member()) for name, member in inspect.getmembers(importlib.machinery.SourceFileLoader('', __file__).load_module()) if inspect.isclass(member)]
path = os.path.join(model_dir, os.path.basename(os.path.splitext(__file__)[0])) + '.xlsx'
with xlsxwriter.Workbook(path, {'strings_to_urls': False, 'nan_inf_to_errors': True}) as workbook:
worksheet = workbook.add_worksheet(args.worksheet)
for j, (key, m) in enumerate(mapper):
worksheet.write(0, j, key)
for i, (name, variable) in enumerate(state_dict.items()):
value = m(name, variable)
worksheet.write(1 + i, j, value)
if hasattr(m, 'format'):
m.format(workbook, worksheet, i, j)
worksheet.autofilter(0, 0, i, len(mapper) - 1)
worksheet.freeze_panes(1, 0)
logging.info(path)
示例14: getProtocolClasses
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
def getProtocolClasses(superclass=ProtocolElement):
"""
Returns all the protocol classes that are subclasses of the
specified superclass. Only 'leaf' classes are returned,
corresponding directly to the classes defined in the protocol.
"""
# We keep a manual list of the superclasses that we define here
# so we can filter them out when we're getting the protocol
# classes.
superclasses = {
ProtocolElement, SearchRequest, SearchResponse
}
thisModule = sys.modules[__name__]
subclasses = []
for name, class_ in inspect.getmembers(thisModule):
if ((inspect.isclass(class_) and
issubclass(class_, superclass) and
class_ not in superclasses)):
subclasses.append(class_)
return subclasses
示例15: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getmembers [as 别名]
def __init__(self, *args, **kwargs):
self.pan_device = kwargs.pop('pan_device', None)
pan.xapi.PanXapi.__init__(self, *args, **kwargs)
pred = lambda x: inspect.ismethod(x) or inspect.isfunction(x) # inspect.ismethod needed for Python2, inspect.isfunction needed for Python3
for name, method in inspect.getmembers(
pan.xapi.PanXapi,
pred):
# Ignore hidden methods
if name[0] == "_":
continue
# Ignore non-api methods
if name in ('xml_result', 'xml_root', 'cmd_xml'):
continue
# Wrapper method. This is used to create
# methods in this class that match the methods in the
# super class, and call the super class methods inside
# a try/except block, which allows us to check and
# analyze the exceptions and convert them to more
# useful exceptions than generic PanXapiErrors.
wrapper_method = PanDevice.XapiWrapper.make_method(name, method)
# Create method matching each public method of the base class
setattr(PanDevice.XapiWrapper, name, wrapper_method)