Skip to content

Instantly share code, notes, and snippets.

@huangsam
Created January 5, 2018 00:02
Show Gist options
  • Save huangsam/40d195cd0bcc540832aa4b75286d14ed to your computer and use it in GitHub Desktop.
Save huangsam/40d195cd0bcc540832aa4b75286d14ed to your computer and use it in GitHub Desktop.
Advanced class utilities
# -*- coding: utf-8 -*-
import importlib
import inspect
import pkgutil
import re
def is_match(entry, pattern):
"""Identify entry match.
Args:
entry: String entry to evaluate regex with.
pattern: Regular expression for matching.
Returns:
True or False.
"""
return re.search(pattern, entry)
def identify_matches(entries, pattern):
"""Identify entry matches.
Args:
entries: List of string entries to evaluate regex with.
pattern: Regular expression for matching.
Returns:
The list of items that satisfy regex pattern.
"""
matches = []
for entry in entries:
if is_match(entry, pattern):
matches.append(entry)
return matches
def identify_classes(package, criteria):
"""Identify classes from given package.
Helpful links:
* https://stackoverflow.com/questions/1707709/list-all-the-modules-that-are-part-of-a-python-package
* https://stackoverflow.com/questions/22119850/get-all-class-names-in-a-python-package
Args:
package: Actual package from an import statement.
criteria: Function for injecting criteria that expects name as input.
Returns:
Set of Analyzer subclasses discovered in package.
"""
classes = set()
path = package.__path__
prefix = package.__name__ + '.'
for importer, modname, ispkg in pkgutil.iter_modules(path, prefix):
if ispkg:
continue
mod = importlib.import_module(modname)
for name, kls in inspect.getmembers(mod, inspect.isclass):
if criteria(name) is True:
classes.add(kls)
return classes
# -*- coding: utf-8 -*-
# https://stackoverflow.com/questions/452969/does-python-have-an-equivalent-to-java-class-forname
def get_class(kls):
parts = kls.split('.')
module = ".".join(parts[:-1])
m = __import__(module)
for comp in parts[1:]:
m = getattr(m, comp)
return m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment