Python dynamic attribute creation

Gregory Ewing greg.ewing at canterbury.ac.nz
Fri Jul 2 05:42:53 EDT 2010


WANG Cong wrote:

> However, I think setattr() is a builtin function, using it exposes the
> *magic* of metaprogramming (or class-programming, if more correct) at a
> first glance.

But, in Python, creating instance variables is *not*
class-programming. It doesn't touch the class at all.

In many OO languages, such as Simula, C++ and Java,
one of the responsibilities of a class is to define
what attributes its instances have. However, that
really comes about because those languages are
statically typed -- it's not an essential principle
of OO at all.

In Python, restricting what attributes an object can
have is *not* considered to be a responsibility of the
class. The class is just a convenient place to put
stuff (mostly methods) that some bunch of objects all
need to have. Anything beyond that is up to the
objects themselves.

It so happens that, in most Python programs, all the
instances of a given class will usually have a well-
defined set of attributes. But Python doesn't go out
of its way to enforce that.

This is just a part of Python's general philosophy of
not requiring declarations. There are very few
declarative constructs in Python -- even class and
function definitions are executable statements that
construct data structures at run time. The only
true declarations are the 'global' and 'nonlocal'
statements, and they only exist because without them
there would be no way to achieve certain things.
They are not there to enforce any kind of static
check.

Why does Python not require declarations? Because it
makes code easier and faster to develop. Instead of
having to spend time and effort writing declarations,
you just get straight on and write the code that does
the actual work. And if you change your mind and need
to move things around, you don't have to perform extra
work to keep the declarations up to date. This can
be a big help in the early stages of development, when
you're feeling your way and the design is fluid. It
also makes the program easier to extend and modify
later.

The downside is that certain kinds of error, that would
be caught at compile time in a more static language,
don't show up until you run the program. But if you're
testing properly -- which you need to do anyway, whatever
language you're using -- they usually show up pretty
soon, and aren't much harder to fix when they do.

Experience has shown that the overall process -- design,
programming, testing and debugging -- tends to be faster
using a dynamic, fluid language such as Python, than
a static one such as C++ or Java. And, many people would
say, more fun as well -- which is a good enough reason
on its own for using Python!

-- 
Greg



More information about the Python-list mailing list