[Tutor] best way to dynamically set class variables?

Alan Gauld alan.gauld at yahoo.co.uk
Wed Nov 7 18:06:31 EST 2018


On 07/11/2018 20:07, Albert-Jan Roskam wrote:

> I should have mentioned that the code ... should be able to convert 
> an *arbitrary* Sql server table into hdf5 format*). 

Umm, yes that would have helped!

>>>> from tables import *
>>>> class Particle(IsDescription):
> ...     name      = StringCol(16)   # 16-character String
> ...     idnumber  = Int64Col()      # Signed 64-bit integer
> ...     ADCcount  = UInt16Col()     # Unsigned short integer
> ...     TDCcount  = UInt8Col()      # unsigned byte
> ...     grid_i    = Int32Col()      # 32-bit integer
> ...     grid_j    = Int32Col()      # 32-bit integer
> ...     pressure  = Float32Col()    # float  (single-precision)
> ...     energy    = Float64Col()    # double (double-precision)
> 
> 
> Imagine having to write this for 100 columns, brrr.

No problem, I've done that dozens of time for production C++ code,
it's business as usual in commercial programming.

Of course I'd get the data from a meta SQL query and feed it into an
emacs macro to generate the code but I'd still have to churn out the
class definitions. (Or I might even write a Python program to generate
the C++ code for me) But it's eminently doable and keeps the rest of the
code simple.

Of course Python allows for dynamic creation of classes so you
can be more subtle than that. :-)

> So the code grabs the sql column names and the datatypes 
> and translates that into the hdf5 equivalent. 

Should be relatively easy to write a function to do that.
I'm not clear if the class definition already exists
or if you are trying to create the class (Based on
the table name maybe?)as well as its attributes?

Also column names are usually instance attributes not
class attributes. Each instance of the class being a
row in the table...


> And pytables uses a class, with class variables, to define this.

No idea what pytables is or what it does so can't comment.

> A classmethod might be nice. I've never used this before, 

If there is some kind of abstract superclass (TableModel
or somesuch?) then a class method there could spin off the
new subclasses.

>  exec() might even be a way

It's a way but it's a bad way! :-)

Another option would be to explore metaclasses
and modify the class creation mechanism


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list