Class optimization at runtime

Dan Sommers me at privacy.net
Tue Aug 3 04:15:50 CEST 2004


On Mon, 2 Aug 2004 16:06:03 -0500,
"Larry Bates" <lbates at swamisoft.com> wrote:

> Kind of hard to tell what you are trying to accomplish
> but I'll try.  Define the class with no if/else statements.
> They only get parsed once.  It is the "class instance"
> creations that may get created millions of times.  They
> will be inside your logical structure.

> class Foo:
>     def __init__(self):
>         # do stuff

> class Bar:
>     def __init__(self):
>         # do stuff

> if option: x=Foo()
> else:      x=Bar()

Similarly:

    class FooWithOption:
        def __init__( self ):
            # whatever

    class FooWithoutOption:
        def __init__( self ):
            # whatever

    if option:
        Foo = FooWithOption
    else:
        Foo = FooWithoutOption

    x = Foo( )

Alternatively:

    module WithOption:
        class Foo:
            # whatever
        class Bar:
            # whatever

    module WithOutOption:
        class Foo:
            # whatever
        class Bar:
            # whatever

    if option:
        from WithOption import *
    else:
        from WithoutOption import *

    x = Foo( )

I guess it depends on how similar the with and without classes are as to
which one will be easier to maintain.

In either case, there's only one test and no additional overhead at
class instantiation time.

> HTH,
> Larry Bates

Regards,
Dan

-- 
Dan Sommers
<http://www.tombstonezero.net/dan/>
Never play leapfrog with a unicorn.



More information about the Python-list mailing list