summaryrefslogtreecommitdiff
path: root/factory/utils.py
diff options
context:
space:
mode:
Diffstat (limited to 'factory/utils.py')
-rw-r--r--factory/utils.py32
1 files changed, 20 insertions, 12 deletions
diff --git a/factory/utils.py b/factory/utils.py
index f845f46..fb8cfef 100644
--- a/factory/utils.py
+++ b/factory/utils.py
@@ -58,20 +58,16 @@ def extract_dict(prefix, kwargs, pop=True, exclude=()):
return extracted
-def declength_compare(a, b):
- """Compare objects, choosing longest first."""
- if len(a) > len(b):
- return -1
- elif len(a) < len(b):
- return 1
- else:
- return cmp(a, b)
-
-
def multi_extract_dict(prefixes, kwargs, pop=True, exclude=()):
"""Extracts all values from a given list of prefixes.
- Arguments have the same meaning as for extract_dict.
+ Extraction will start with longer prefixes.
+
+ Args:
+ prefixes (str list): the prefixes to use for lookups
+ kwargs (dict): the dict from which values should be extracted
+ pop (bool): whether to use pop (True) or get (False)
+ exclude (iterable): list of prefixed keys that shouldn't be extracted
Returns:
dict(str => dict): a dict mapping each prefix to the dict of extracted
@@ -79,10 +75,22 @@ def multi_extract_dict(prefixes, kwargs, pop=True, exclude=()):
"""
results = {}
exclude = list(exclude)
- for prefix in sorted(prefixes, cmp=declength_compare):
+ for prefix in sorted(prefixes, key=lambda x: -len(x)):
extracted = extract_dict(prefix, kwargs, pop=pop, exclude=exclude)
results[prefix] = extracted
exclude.extend(
['%s%s%s' % (prefix, ATTR_SPLITTER, key) for key in extracted])
return results
+
+
+def import_object(module_name, attribute_name):
+ """Import an object from its absolute path.
+
+ Example:
+ >>> import_object('datetime', 'datetime')
+ <type 'datetime.datetime'>
+ """
+ module = __import__(module_name, {}, {}, [attribute_name], 0)
+ return getattr(module, attribute_name)
+