def get_instance_public_methods(instance):
"""Retrieves an objects public methods
:param instance: The instance of the class to inspect
:rtype: dict
:returns: A dictionary that represents an instance's methods where
the keys are the name of the methods and the
values are the handler to the method.
"""
instance_members = inspect.getmembers(instance)
instance_methods = {}
for name, member in instance_members:
if not name.startswith('_'):
if inspect.ismethod(member):
instance_methods[name] = member
return instance_methods
python类getmembers()的实例源码
def remove_plugin(self, name: str):
plugin = self.plugins.pop(name, None)
if plugin is None:
return plugin
for name, member in inspect.getmembers(plugin):
# Remove IRC events
if isinstance(member, event.event):
self.remove_irc_event(member)
# Remove listeners
elif name.startswith(('on_', 'handle_')):
self.remove_listener(member)
try:
unloader = getattr(plugin, 'unload')
except AttributeError:
pass
else:
unloader()
return plugin
def report(aresObj):
""" Display all the HTML components """
modulesPath = tmpplPath = os.path.join(aresObj.http['DIRECTORY'], "..", "ares", "Lib", 'html')
sys.path.append(modulesPath)
aresObj.title("A suite of HTML components available")
classNames = []
for aresMod in os.listdir(modulesPath):
if aresMod.endswith(".py") and aresMod.startswith("AresHtml") and not aresMod.startswith("AresHtmlGraph") and aresMod != 'AresHtml.py':
mod = __import__(aresMod.replace(".py", ""))
for name, cls in inspect.getmembers(mod):
if inspect.isclass(cls) and hasattr(cls, 'alias'):
classNames.append({'Class': aresObj.href(name, 'AresDocHtmlItem',
{'html_module': aresMod, 'html_class': name, 'html_alias': cls.alias}, cssCls=''),
'Ares Module': aresMod,
#'Documentation': aresObj.external_link('Website', cls.reference),
})
aresObj.table(classNames, [{'colName': 'Class', 'type': 'object'},
{'colName': 'Ares Module'},
#{'colName': 'Documentation', 'type': 'object'}
], 'Ares Module Documentation')
def get_celery_tasks_from_module(self, submodule):
"""
Extract all celery tasks from a module.
Celery tasks are functions decorated by @celery_app.task(...)
This decorator transform the function into a class child of
celery.local.PromiseProxy
"""
tasks = {}
functions = inspect.getmembers(submodule)
for func in functions:
obj_type = type(func[1])
if obj_type.__module__ != "celery.local":
continue
tasks[func[0]] = func[1]
return tasks
def get_torrent_client(torrent_settings: Dict[str, Any]) -> TorrentClient:
client = None
torrent_module = None
for module_name in modules_name:
if module_name == torrent_settings['client']:
if module_name not in sys.modules:
full_package_name = '%s.%s' % ('core.downloaders.torrent', module_name)
torrent_module = __import__(full_package_name, fromlist=[module_name])
else:
torrent_module = module_name
if not torrent_module:
return torrent_module
for _, obj in inspect.getmembers(torrent_module):
if inspect.isclass(obj) and hasattr(obj, 'type') and 'torrent_handler' in getattr(obj, 'type'):
client = obj(
torrent_settings['address'],
torrent_settings['port'],
torrent_settings['user'],
torrent_settings['pass'],
secure=not torrent_settings['no_certificate_check'],
)
return client
def update_inputs(av_states, socket_send, *input_variable_names):
# From each input variable name, extract the function name, ids of AvStates to be passed as arguments,
# and the corresponding function from psaltlib.Inputs. Call the function with the id-key'd AvStates as
# arguments. Aggregate results in order in a list.
input_state = []
for term in input_variable_names:
term_elements = re.split('_', term)
function_name = term_elements[0]
av_id_args = term_elements[1:]
args = []
for av_id in av_id_args:
args.append(av_states[int(av_id)])
args.append(socket_send)
func = [o for o in getmembers(psaltlib.Inputs) if isfunction(o[1]) and
o[0] == function_name]
input_state.append(func[0][1](*args))
return input_state
def load_from(self, load_type, load_string):
def isNotClass(element):
return not isinstance(element, type)
self.__load_iters([member for member in inspect.getmembers(self.caller, isNotClass)], load_type, load_string)
def get_app_models(app):
from .model import Model
try:
models_module = importlib.import_module('{}.models'.format(app.name))
for name, obj in inspect.getmembers(models_module):
if inspect.isclass(obj) and issubclass(obj, Model):
if obj.__name__ == 'TimedModel':
continue
yield name, obj
except Exception as e:
return list()
def get_design(modname):
"""Given a module name, return a Design class."""
fullmodname = f"zellij.design.{modname}"
mod = importlib.import_module(fullmodname)
classes_in_mod = []
for _, val in inspect.getmembers(mod):
if inspect.isclass(val):
if inspect.getmodule(val) is mod:
classes_in_mod.append(val)
assert len(classes_in_mod) == 1
return classes_in_mod[0]
def get_members(self, app):
return inspect.getmembers(app)
def iterate_proto_msg(module, base):
for name, cls in getmembers(module):
if isclass(cls) and issubclass(cls, Message):
yield base + name, cls
yield from iterate_proto_msg(cls, base + name + '.')
# Routine for saving data returned by an extractor
def _all_message_field_names(self):
return [
name for name, value in getmembers(
Message,
lambda v: isinstance(v, property)
)
]
def allmethods(cl):
methods = {}
for key, value in inspect.getmembers(cl, _is_some_method):
methods[key] = 1
for base in cl.__bases__:
methods.update(allmethods(base)) # all your base are belong to us
for key in methods.keys():
methods[key] = getattr(cl, key)
return methods
def _load_mods(opts, mods, search_dir, prefix):
'''
opts: The seralized config file
reaction_dir: A directory to search for reaction modules
'''
loaded = dict()
for mod_to_load in mods:
mod = imp.load_source(mod_to_load, os.path.join(search_dir, mod_to_load))
for func_def in inspect.getmembers(mod, inspect.isfunction):
func_mod_delimited = '{0}.{1}.{2}'.format(prefix, mod_to_load.rstrip('.py'), func_def[0])
loaded[func_mod_delimited] = func_def[1]
return loaded
def MYPPRINT(obj, name = None):
import inspect, pprint
if isinstance(obj, dict) or isinstance(obj, list):
pprint.pprint(obj)
elif hasattr(obj, '__call__'):
pprint.pprint(inspect.getargspec(obj))
else:
pprint.pprint(inspect.getmembers(obj))
return
def list_markets(self):
logging.debug('list_markets')
for filename in glob.glob(os.path.join(public_markets.__path__[0], "*.py")):
module_name = os.path.basename(filename).replace('.py', '')
if not module_name.startswith('_'):
module = __import__("public_markets." + module_name)
test = eval('module.' + module_name)
for name, obj in inspect.getmembers(test):
if inspect.isclass(obj) and 'Market' in (j.__name__ for j in obj.mro()[1:]):
if not obj.__module__.split('.')[-1].startswith('_'):
print(obj.__name__)
sys.exit(0)
def discover_components(package, directory, base_class):
"""Discover implementations of a base class in a package.
Parameters
----------
package : str
Package name
directory : str
Directory of the package to which is inspected.
base_class : object
Base class of objects to discover
Returns
-------
list : all subclasses of `base_class` inside `directory`
"""
components = list()
for module_loader, module_name, ispkg in pkgutil.iter_modules(
[directory]):
full_module_name = "%s.%s" % (package, module_name)
if full_module_name not in sys.modules and not ispkg:
module = importlib.import_module(full_module_name)
for member_name, obj in inspect.getmembers(module):
if inspect.isclass(obj) and issubclass(base_class, obj):
classifier = obj
components.append(classifier)
return components
def magic():
"""
Returns a string which represents Python code that copies instance
variables to their local counterparts. I.e:
var = self.var
var2 = self.var2
"""
s = ""
for var, value in inspect.getmembers(sys._getframe(1).f_locals["self"]):
if not (var.startswith("__") and var.endswith("__")):
s += var + " = self." + var + "\n"
return s
def __init__(self, bot):
self.bot = bot
# Add commands as search subcommands
for name, command in inspect.getmembers(self):
if isinstance(command, commands.Command) and command.parent is None and name != "search":
self.bot.add_command(command)
self.search.add_command(command)
# Add search subcommands as subcommands of corresponding commands
self.search_subcommands = ((self.imgur, "Resources.imgur"), (self.youtube, "Audio.audio"))
for command, parent_name in self.search_subcommands:
utilities.add_as_subcommand(self, command, parent_name, "search")
def __init__(self, bot):
self.bot = bot
self.players = {}
for name, command in inspect.getmembers(self):
if isinstance(command, commands.Command) and command.parent is None and name != "audio":
self.bot.add_command(command)
self.audio.add_command(command)