How can I make something like this?
class Form(object, metaclass=...):
pass
class Field(object):
def __init__(self, nested_form_class=None):
self.nested_form_class = nested_form_class
class TaskForm(Form):
children = Field(nested_form_class=TaskForm)
Renders:
NameError: name 'TaskForm' is not defined
The error occurs on the line defining the children attribute.
I use class attributes in the __new__ function of the metaclass and I can not move it to __init__ function of current class.
My metaclass (Like in django framework):
class FormMeta(type):
"""
Meta class for extract fields from model
"""
def __new__(mcs, name, bases, attrs):
found_fields = dict()
for k, v in attrs.items():
if isinstance(v, Field):
found_fields[k] = v
attrs['found_fields'] = found_fields
new_class = super().__new__(mcs, name, bases, attrs)
parent_fields = {}
for base in reversed(new_class.__mro__):
# Collect fields from base class.
if hasattr(base, 'found_fields'):
parent_fields.update(base.found_fields)
# Disable reordered fields.
for attr, value in base.__dict__.items():
if value is None and attr in parent_fields:
parent_fields.pop(attr)
new_class.base_fields = parent_fields
new_class.found_fields = parent_fields
return new_class