[Tutor] best way to dynamically set class variables?

Albert-Jan Roskam sjeik_appie at hotmail.com
Wed Nov 7 15:07:07 EST 2018



On 7 Nov 2018 20:36, Mats Wichmann <mats at wichmann.us> wrote:
Not sure what you're after, but what's wrong with just setting them?

Parent.avar = "a class var"

Hi Alan, Mats,

I should have mentioned that the code is part of a function sql_to_hdf5. So it should be able to convert an *arbitrary* Sql server table into hdf5 format*). But even if it was just one specific table: it's quite cumbersome to write the column names (class variable names) and the target hdf5 data types (class variable values) for, say, a hundred columns. This is an example from the pytables website:


>>> 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.

So the code grabs the sql column names and the datatypes (easy with sqlalchemy) and translates that into the hdf5 equivalent. And pytables uses a class, with class variables, to define this.

A classmethod might be nice. I've never used this before, but I'll try this (I did try __new__ this afternoon, but it looked even more complicated). And it just occurred to me that exec() might even be a way (namedtuple does it, too). Or should I now grab my coat for even mentioning exec? :-)))

Best wishes,
Albert-Jan

*) I tried using pandas to_hdf for this, but this does not work wel with mixed dtypes, NULL values, and chunkwise reading.


More information about the Tutor mailing list