akaariai / ast_model

Speed up Django's model initialization by using AST

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

    A class deriving from ASTModel will use a custom __init__ method. The
    properties of the custom __init__ are as follows:
        - Signals are sent only when needed.
        - If there is exactly as much args to __init__ as it has fields
          a fast path is taken. The fast path is a rewrite of:
              for attname, val in izip(attnames, args):
                  setattr(self, attname, val)
          into this:
              self.att1, self.att2, self.att3, ... = args
        - Otherwise the init method should work normally. Although this is
          _very_ experimental.

    AST is used to dynamically alter the original Model.__init__ into a new
    __init__ method which has the abovementioned optimizations done. The AST
    generation has a lot of comments, so it should be possible to follow what
    is done.

    Requirements: Python 2.6 or Python 2.7.

    Usage:
        from astmodel import ASTModel
        class SomeModel(ASTModel):
            # If you want to force init signal sending, then set
            # send_init_signals = True
            # otherwise, init_signals are sent only if the Model
            # contains ImageFields or GenericForeignKeys. 
            normal class definition otherwise
                                              

    Known bugs and limitations:
      - Eats your data. In other words, use at your own risk.

    I have tested this on Django trunk as of 2011-12-04, all tests passed.

    The speed difference (using the included tester) is as follows:
       raw init speed, 10000 objects, 11 fields:
           astmodel: 0.18s (signals to other models or not)
           normal model: 0.37s
           with signals: 0.55s (to _other_ model that the tested model!)

About

Speed up Django's model initialization by using AST


Languages

Language:Python 100.0%