how-to do black magic (using metaclass?)

Sean Ross frobozz_electric at hotmail.com
Fri May 16 13:34:59 EDT 2003


After seeing this posting, I've updated my recipe,
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157768, with one
more convenience method. autoproperties() will automate the creation of
readable and writeable properties for your classes.

>From reading your post, I gather that you want to be able to do is something
like the following:

#info.txt file contents
foo=1,bar=2,fro=3,boz=4

then in your Python program, you can do things like this:

# assumes you've added rowo.py (see recipe) module to your path
from rowo import autoproperties

# read and prepare property information from file
fd = open('./info.txt')
info = fd.readline()
info = info.split(',')
info = [tuple(i.split('=')) for i in info]
infodict = dict(info)

# use autoproperties() to automate the creation of
# readable and writeable properties for instances of MyClass
class MyClass(object):
    autoproperties(**infodict)

instance = MyClass()
print 'instance.foo: %s' % instance.foo
print 'instance.bar: %s' % instance.bar
instance.foo = 'changed'
print 'instance.foo: %s' % instance.foo
print 'instance._MyClass__foo: %s' % instance._MyClass__foo

# This outputs...
instance.foo: 1
instance.bar: 2
instance.foo: changed
instance._MyClass__foo: changed

This is the behaviour I think you were asking for. If you really want to use
metaclasses, you can use the following recipe as a starting point:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/197965

I'm a bit curious as to why you would want to be able to create properties
from a file, especially if you will not know in advance what the names of
those created properties will be. How did you plan to use them?

Anyway, I hope this is helpful to you,
Sean

>
> The recipe
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157768
>
> and its (long) discussion should give you a head start.
>

Heh. It /is/ a very long discussion isn't it...Maybe I can get Mr.Ascher or
the webmaster to trim it down a little. We'll see...







More information about the Python-list mailing list