# dynamic class instantiation

Volker Grabsch volker_grabsch at v.notjusthosting.com
Tue Jan 31 23:11:14 EST 2006

Ognen Duzlevski wrote:
> Kent Johnson <kent at kentsjohnson.com> wrote:
>> Ognen Duzlevski wrote:
>> > Say I got "page" as a string. How do I go about
>> > instantiating a class from this piece of information? To make it
>> > more obvious how do I create the page() class based on the "page"
>> > string I have?
>
>> Use getattr().
>
> Hi Kent, this is exactly what I was looking for. I can't believe I didn't think
> of getattr() myself! ;(

However, remember that this solves your problem just temporarily.

Your main problem is still a deep design failure. Code generators are
relicts, hard to maintain, and usually just plain ugly. Your application
isn't that special.

I'm sure you could replace 2/3 of your code with something much simpler
(and shorter!) just by not inventing a new language and using the power

People often think that a new language simplifies their problem, and that
code generation saves work. However, a the code of the code generator has
to be maintained, too! That's what most people are realizing too late.
Also, simple class inheritance, closures and similar mechanisms save a
lot of work, too, they do their job even better than a code generator,
and they are a charm to maintain.

Even the "magic" (AKA meta-classes :-)) may be hard, but it's usually a
much simpler and cleaner approach than a code generator.

Don't generate Python code. Python is neither Java nor C, it's dynamic!

Greets,

Volker

--
Volker Grabsch
---<<(())>>---
\frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt
[G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}}