design question: no new attributes

Bruno Desthuilliers bdesth.quelquechose at
Thu Mar 1 22:53:35 CET 2007

Alan Isaac a écrit :
> "Bruno Desthuilliers" <bdesth.quelquechose at> wrote in
> message news:45e60fdc$0$30655$426a34cc at
>>I don't share your definition of "reasonable". But you should have
>>guessed by now
> My view may be shaped by a different experience.
> I have found dynamic attribute creation convenient
> when doing something "quick and dirty", but I have
> never wanted it as a design feature in a more serious
> project.
> Can you give me an example where design considerations
> make dynamic attribute creation particularly desirable?

Let's consider an imaginary ORM (or it could be an "object-ldap mapper", 
or just any other stuff where it may be useful to have 'smart 
attributes', like Plone's Archetype or FormEncode or...):

class Person(Schema):
    firstname = TextField(empty=False, format=str.capitalize)
    lastname = TextField(empty=False, format=str.upper)
    nickname = TextField(empty=False, format=str.lower, dbfield="login")

p = Person(firstname="joe", lastname="Hacker")

=> "Joe"
=> "joe"

=> 'firstname'

I let you try to write the SchemaType metaclass without dynamically 
adding attributes to either the Person class (remember that classes are 
objects too) and/or the TextField instances...

Let's consider the controller part of a web MVC application. You want to 
manage security in a declarative way.

class PageController(Controller):
   def view(self):
      # code here

   def edit(self):
      # code here


What do you think this decorator will do ? yes, that's right: annotate 
the action methods with needed perms, so the relevant part of the 
framework can take appropriate action...

As a side note :  in Python, *all* attributes are "dynamically created". 
Class attributes are dynamically added to the class object by it's 
metaclass, instance attributes are dynamically added to the instance, 
usually - but not necessarily - by the __init__ method. Now the __init__ 
method is nothing more than a wrapper around the __init__ function, 
which itself takes the (bare) instance as argument. Writing methods 
within the class statement body makes things clearer, but is by no mean 

class Foo(object):

def init_foo(foo, name): = name

Foo.__init__ = init_foo

Like a lot of other tools (HOFs, metaclasses, descriptors, generators 
etc), dynamic attribute creation looks mostly like a useless gadget when 
you never used it before - because it's not part of your "mind map", you 
don't naturally use it in your design.

My 2 cents

More information about the Python-list mailing list