[Python-ideas] Lazy creation of module level functions and classes

Neil Schemenauer nas-python-ideas at arctrix.com
Thu Sep 7 22:49:14 EDT 2017


This is an idea that come out of the lazy loading modules idea.
Larry Hastings mentioned what a good improvement this was for PHP.
I think it would help a lot of Python too.  Very many functions and
classes are not actually needed but are instantiated anyhow.

Back of napkin idea:

Write AST transformer tool, change top-level functions and classes
to be like properties (can use __class__ I guess)

Transform is something like:

# old code
def inc(x):
    return x + 1

# transformed code
def __make_inc(code=<code object bytes>):
    obj = eval(code)
    _ModuleClass.inc = obj # only do eval once
    return obj
inc = property(__make_inc)

Totally seat of pants idea but I can't think of a reason why it
shouldn't work.  It seems much more powerful than lazying loading
modules.  In the lazy module case, you load the whole module if any
part is touched.  Many modules only have a small fraction of their
functions and classes actually used.

If this transformer idea works, the standard Python compiler could
be changed to do the above stuff, no transformer needed.


More information about the Python-ideas mailing list