<s> import collections <EOL> from steel . common import data <EOL> class NameAwareOrderedDict ( collections . OrderedDict ) : <EOL> """<STR_LIT>""" <EOL> def __setitem__ ( self , name , obj ) : <EOL> if len ( data . field_stack ) == <NUM_LIT:1> : <EOL> super ( NameAwareOrderedDict , self ) . __setitem__ ( name , obj ) <EOL> if hasattr ( obj , '<STR_LIT>' ) : <EOL> obj . set_name ( name ) <EOL> data . field_stack [ - <NUM_LIT:1> ] . append ( obj ) <EOL> class DeclarativeMetaclass ( type ) : <EOL> @ classmethod <EOL> def __prepare__ ( cls , name , bases , ** options ) : <EOL> data . field_options = options <EOL> data . field_stack = [ [ ] ] <EOL> return NameAwareOrderedDict ( ) <EOL> def __new__ ( cls , name , bases , attrs , ** options ) : <EOL> return type . __new__ ( cls , name , bases , attrs ) <EOL> def __init__ ( cls , name , bases , attrs , ** options ) : <EOL> cls . _fields = collections . OrderedDict ( ) <EOL> for base in bases : <EOL> if hasattr ( base , '<STR_LIT>' ) : <EOL> cls . _fields . update ( base . _fields ) <EOL> for name , attr in attrs . items ( ) : <EOL> if name in cls . _fields and attr is None : <EOL> del cls . _fields [ name ] <EOL> if hasattr ( attr , '<STR_LIT>' ) : <EOL> attr . attach_to_class ( cls ) <EOL> data . field_options = { } <EOL> data . field_stack = [ [ ] ] <EOL> class DeclarativeFieldMetaclass ( type ) : <EOL> @ classmethod <EOL> def __prepare__ ( cls , name , bases , ** options ) : <EOL> return NameAwareOrderedDict ( ) <EOL> def __init__ ( cls , name , bases , attrs , ** options ) : <EOL> cls . arguments = { } <EOL> for base in reversed ( bases ) : <EOL> if hasattr ( base , '<STR_LIT>' ) : <EOL> cls . arguments . update ( base . arguments ) <EOL> for name , attr in attrs . items ( ) : <EOL> if name in cls . arguments and attr is None : <EOL> del cls . arguments [ name ] <EOL> if hasattr ( attr , '<STR_LIT>' ) : <EOL> attr . attach_to_class ( cls ) <EOL> def __call__ ( cls , * args , ** kwargs ) : <EOL> if data . field_options : <EOL> options = { } <EOL> for name , value in data . field_options . items ( ) : <EOL> if name in cls . arguments : <EOL> options [ name ] = value <EOL> options . update ( kwargs ) <EOL> else : <EOL> options = kwargs <EOL> return super ( DeclarativeFieldMetaclass , cls ) . __call__ ( * args , ** options ) <EOL> class AttributeInstance : <EOL> def __init__ ( self , field , instance ) : <EOL> self . field = field <EOL> self . instance = instance <EOL> def __enter__ ( self ) : <EOL> if self . instance is not None : <EOL> data . instance_stack [ hash ( self . field ) ] . append ( self . instance ) <EOL> def __exit__ ( self , exception_type , exception , traceback ) : <EOL> if self . instance is not None : <EOL> data . instance_stack [ hash ( self . field ) ] . pop ( ) </s>
