root / env / lib / python2.7 / site-packages / south / utils / __init__.py @ d1a4905f
History | View | Annotate | Download (1.89 KB)
1 |
"""
|
---|---|
2 |
Generally helpful utility functions.
|
3 |
"""
|
4 |
|
5 |
|
6 |
def _ask_for_it_by_name(name): |
7 |
"Returns an object referenced by absolute path."
|
8 |
bits = name.split(".")
|
9 |
|
10 |
## what if there is no absolute reference?
|
11 |
if len(bits)>1: |
12 |
modulename = ".".join(bits[:-1]) |
13 |
else:
|
14 |
modulename=bits[0]
|
15 |
|
16 |
module = __import__(modulename, {}, {}, bits[-1]) |
17 |
|
18 |
if len(bits) == 1: |
19 |
return module
|
20 |
else:
|
21 |
return getattr(module, bits[-1]) |
22 |
|
23 |
|
24 |
def ask_for_it_by_name(name): |
25 |
"Returns an object referenced by absolute path. (Memoised outer wrapper)"
|
26 |
if name not in ask_for_it_by_name.cache: |
27 |
ask_for_it_by_name.cache[name] = _ask_for_it_by_name(name) |
28 |
return ask_for_it_by_name.cache[name]
|
29 |
ask_for_it_by_name.cache = {} |
30 |
|
31 |
|
32 |
def get_attribute(item, attribute): |
33 |
"""
|
34 |
Like getattr, but recursive (i.e. you can ask for 'foo.bar.yay'.)
|
35 |
"""
|
36 |
value = item |
37 |
for part in attribute.split("."): |
38 |
value = getattr(value, part)
|
39 |
return value
|
40 |
|
41 |
def auto_through(field): |
42 |
"Returns if the M2M class passed in has an autogenerated through table or not."
|
43 |
return (
|
44 |
# Django 1.0/1.1
|
45 |
(not field.rel.through)
|
46 |
or
|
47 |
# Django 1.2+
|
48 |
getattr(getattr(field.rel.through, "_meta", None), "auto_created", False) |
49 |
) |
50 |
|
51 |
def auto_model(model): |
52 |
"Returns if the given model was automatically generated."
|
53 |
return getattr(model._meta, "auto_created", False) |
54 |
|
55 |
def memoize(function): |
56 |
"Standard memoization decorator."
|
57 |
name = function.__name__ |
58 |
_name = '_' + name
|
59 |
|
60 |
def method(self): |
61 |
if not hasattr(self, _name): |
62 |
value = function(self)
|
63 |
setattr(self, _name, value) |
64 |
return getattr(self, _name) |
65 |
|
66 |
def invalidate(): |
67 |
if hasattr(method, _name): |
68 |
delattr(method, _name)
|
69 |
|
70 |
method.__name__ = function.__name__ |
71 |
method.__doc__ = function.__doc__ |
72 |
method._invalidate = invalidate |
73 |
return method
|