Created
October 5, 2010 11:12
-
-
Save akx/611369 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect, types | |
verboten = set(["queryset", "initial", "error_messages"]) | |
NotNone = object() | |
memo = set() | |
def _make_ctor_args(obj): | |
params = [] | |
namesSeen = set() | |
allArgs = [] | |
for cls in inspect.getmro(obj.__class__): | |
ctor = cls.__init__ | |
if cls == object or not isinstance(ctor, types.MethodType): | |
continue | |
args, _, _, defs = inspect.getargspec(ctor) | |
if not defs: | |
defs = [NotNone] * len(args) | |
for arg, default in zip(args, defs)[1:]: | |
if arg not in namesSeen: | |
allArgs.append((arg, default)) | |
namesSeen.add(arg) | |
for arg, default in allArgs: | |
val = getattr(obj, arg, None) | |
if arg not in verboten and val != default: | |
r = repr(val) | |
if isinstance(val, list): | |
r = "[%s]" % ", ".join(make_full_ctor(v) for v in val) | |
elif r.startswith("<"): # Non-canonical, attempt to recurse ctor | |
r = make_full_ctor(val) | |
params.append("%s = %s" % (arg, r)) | |
return ", ".join(params) | |
def make_full_ctor(obj): | |
i = id(obj) | |
if i in memo: | |
return repr(obj) | |
memo.add(i) | |
qname = "%s.%s" % ( | |
obj.__class__.__module__, | |
obj.__class__.__name__ | |
) | |
return "%s(%s)" % (qname, _make_ctor_args(obj)) | |
def reverse_engineer_modelform(form_class): | |
inst = form_class() | |
print "class %s(forms.ModelForm):" % (form_class.__name__) | |
for name, field in sorted(inst.fields.iteritems(), key = lambda (n,f): f.creation_counter): | |
print "\t%s = %s" % (name, make_full_ctor(field)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment