Coverage for /usr/local/lib/python3.10/site-packages/opal_common-0.0.0-py3.10.egg/opal_common/emport.py: 36%
95 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-10 11:54 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-10 11:54 +0000
1"""From https://github.com/orweis/emport."""
3import collections
4import glob
5import inspect
6import os
7import sys
9__author__ = "orw"
12class ObjectUtils(object):
13 @staticmethod
14 def is_derived_of(obj, possible_parent_class):
15 if hasattr(obj, "__bases__"):
16 return possible_parent_class in inspect.getmro(obj)
17 else:
18 return False
20 @staticmethod
21 def get_properties(obj):
22 def filter(x):
23 return not isinstance(x, collections.Callable)
25 return {
26 k: v for k, v in inspect.getmembers(obj, filter) if not k.startswith("__")
27 }
29 @staticmethod
30 def get_members_who_are_instance_of(obj, class_type):
31 def filter(x):
32 return isinstance(x, class_type)
34 return inspect.getmembers(obj, filter)
36 @classmethod
37 def get_class_members_who_derive_of(cls, obj, parent_class):
38 def filter(x):
39 return (
40 inspect.isclass(x)
41 and cls.is_derived_of(x, parent_class)
42 and list(inspect.getmro(x)).index(parent_class) != 0
43 )
45 return inspect.getmembers(obj, filter)
48class PyFrame(object):
49 def __init__(self):
50 self._frame = inspect.currentframe()
52 def __enter__(self):
53 return self._frame.f_back
55 def __exit__(self, exc_type, exc_value, traceback):
56 del self._frame
59class Emport(object):
60 def __init__(self, module, members):
61 self.__original__ = module
62 self._members = []
63 for member in members:
64 self._members.append(member[1])
65 setattr(self, member[0], member[1])
67 def get_original_module(self):
68 return self.__original__
70 def get_members_list(self):
71 return self._members
73 def get_flat_list(self):
74 """:return: all the members of this Emport (And submodules) as one
75 list."""
76 res = []
77 for member in self._members:
78 # if a member is an Emport itself flatten it as well
79 if isinstance(member, Emport):
80 res += member.get_flat_list()
81 else:
82 res.append(member)
83 return res
85 def __repr__(self):
86 return "EMPORT - %s" % self.__original__
89def get_caller_module(depth=0):
90 """:param depth: stack depth of the caller.
92 0 == yourself, 1 == your parent
93 :return: the module object of the caller function (in set stack depth)
94 """
95 with PyFrame() as frame:
96 for i in range(0, depth):
97 frame = frame.f_back
98 return sys.modules[frame.f_globals["__name__"]]
101def co_to_dict(co):
102 return {
103 "co_argcount": co.co_argcount,
104 "co_nlocals": co.co_nlocals,
105 "co_stacksize": co.co_stacksize,
106 "co_flags": co.co_flags,
107 "co_consts": co.co_consts,
108 "co_names": co.co_names,
109 "co_varnames": co.co_varnames,
110 "co_filename": co.co_filename,
111 "co_name": co.co_name,
112 "co_firstlineno": co.co_firstlineno,
113 "co_lnotab": co.co_lnotab,
114 }
117def get_caller(depth=0):
118 """:param depth: stack depth of the caller.
120 0 == yourself, 1 == your parent
121 :return: the frame object of the caller function (in set stack depth)
122 """
123 with PyFrame() as frame:
124 for i in range(0, depth):
125 frame = frame.f_back
126 return co_to_dict(frame.f_code)
129def emport_by_class(from_path, cls, import_items=None):
130 """Wrap __import__ to import modules and filter only classes deriving from
131 the given cls.
133 :param from_path: dot separated package path
134 :param cls: class to filter import contents by
135 :param import_items: the items to import form the package path (can
136 also be ['*'])
137 :return: an Emport object with contents filtered according to given
138 cls
139 """
140 import_items = import_items or ["*"]
141 module_obj = __import__(from_path, globals(), locals(), import_items, 0)
142 clean_items = ObjectUtils.get_class_members_who_derive_of(module_obj, cls)
143 for sub_name, sub_module in ObjectUtils.get_members_who_are_instance_of(
144 module_obj, module_obj.__class__
145 ):
146 results = ObjectUtils.get_class_members_who_derive_of(sub_module, cls)
147 # Keep only modules with sub values
148 if len(results) > 0:
149 clean_sub_module = Emport(sub_module, results)
150 clean_items.append((sub_name, clean_sub_module))
151 clean_module = Emport(module_obj, clean_items)
152 return clean_module
155def emport_objects_by_class(from_path, cls, import_items=None):
156 """Wrap __import__ to import modules and filter only classes deriving from
157 the given cls Return a flat list of objects without the modules themselves.
159 :param from_path: dot separated package path
160 :param cls: class to filter import contents by
161 :param import_items: the items to import form the package path (can
162 also be ['*'])
163 :return: an Emport object with contents filtered according to given
164 cls
165 """
166 results = []
167 import_items = import_items or ["*"]
168 module_obj = __import__(from_path, globals(), locals(), import_items, 0)
169 # direct objects
170 clean_items = ObjectUtils.get_class_members_who_derive_of(module_obj, cls)
171 results.extend(clean_items)
172 # nested
173 for sub_name, sub_module in ObjectUtils.get_members_who_are_instance_of(
174 module_obj, module_obj.__class__
175 ):
176 objects = ObjectUtils.get_class_members_who_derive_of(sub_module, cls)
177 results.extend(objects)
178 return results
181def dynamic_all(init_file_path):
182 """Return a list of all the py files in a dir usage (in __init__.py file) :
184 from emport import dynamic_all __all__ = dynamic_all(__file__)
185 """
186 modules = glob.glob(os.path.join(os.path.dirname(init_file_path), "*.py*"))
187 target_modules = set([])
188 for module in modules:
189 name = os.path.splitext(os.path.basename(module))[0]
190 if os.path.isfile(module) and not name.startswith("_"):
191 target_modules.add(name)
192 return list(target_modules)